【问题标题】:Form with nested models doesn't update nor give nested params具有嵌套模型的表单不更新也不提供嵌套参数
【发布时间】:2013-02-27 23:26:49
【问题描述】:

在 rails 3.2.* 我有一个 has_one belongs_to 嵌套模型,如下所示:

class Unicycle < ActiveRecord::Base
  attr_accessible :brand, :wheel, :wheel_attributes
  has_one :wheel
  accepts_nested_attributes_for :wheel
end

class Wheel < ActiveRecord::Base
  attr_accessible :diameter, :unicycle
  belongs_to :unicycle
end

我的控制器看起来像这样:

class UnicyclesController < ApplicationController
  def index
    @unicycles = Unicycle.all
  end

  def edit
    @unicycle = Unicycle.find_by_id params[:id]
  end

  def update
    @unicycle = Unicycle.find_by_id params[:id]
    if @unicycle.update_attributes! params[:unicycle]
      redirect_to unicycles_path
    else
      render 'edit'
    end
  end
end

我的 edit.html.erb 是这样的:

<%= form_for @unicycle do |formbuilder| %>
  <%= formbuilder.text_field :brand %>

  <%= fields_for @unicycle.wheel do |fieldbuilder| %>
    <%= fieldbuilder.number_field :diameter %>
  <% end %>

  <%= formbuilder.submit %>
<% end %>

但是当我更新时,对 wheel.diameter 所做的更改会被忽略。

我发现即使我的 fields_for 调用嵌套在 edit.html.erb 中的 form_for 块中,发送到我的更新函数的参数也没有嵌套

参数包含:

 {"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"owiV5xwbbt+ft8h4K4bIqshp5I6jrlj5XWEKeVXpoCQ=",
 "unicycle"=>{"brand"=>"Unibike"},
 "wheel"=>{"diameter"=>"70"},
 "commit"=>"Update Unicycle",
 "action"=>"update",
 "controller"=>"unicycles",
 "id"=>"1"}

但根据 rails 文档 (ActiveRecordNestedAttributes),wheel 参数实际上应该像这样嵌套在 unicycle 中:

 "unicycle"=>{"brand"=>"Unibike", "wheel"=>{"diameter"=>"68"}},

我在这里错过了什么?

【问题讨论】:

    标签: ruby-on-rails nested-forms nested-attributes params


    【解决方案1】:

    这是生成嵌套字段的方式:

    # ...
    <%= formbuilder.fields_for :wheel do |fieldbuilder| %>
      <%= fieldbuilder.number_field :diameter %>
    <% end %>
    # ...
    

    【讨论】:

    • 好发现!现在就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多