在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
块中,发送到我的更新功能的参数也没有嵌套
Params包含:
{"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 params应该真的嵌套在unicycle中:
"unicycle"=>{"brand"=>"Unibike", "wheel"=>{"diameter"=>"68"}},
我在这里缺少什么?
答案 0 :(得分:0)
这是生成嵌套字段的方法:
# ...
<%= formbuilder.fields_for :wheel do |fieldbuilder| %>
<%= fieldbuilder.number_field :diameter %>
<% end %>
# ...