0

在 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调用嵌套form_for在 edit.html.erb 的块中,发送到我的更新函数的参数也不是嵌套的

参数包含:

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

但根据 rails 文档(ActiveRecordNestedAttributes),车轮参数应该真正嵌套在 unicycle 中,如下所示:

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

我在这里想念什么?

4

1 回答 1

0

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

# ...
<%= formbuilder.fields_for :wheel do |fieldbuilder| %>
  <%= fieldbuilder.number_field :diameter %>
<% end %>
# ...
于 2013-02-27T23:57:18.643 回答