2013-02-27 93 views
0

在軌3.2 *我有一個HAS_ONE belongs_to的嵌套模式,像這樣:表格嵌套模型不更新也不給嵌套PARAMS

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 

我CONTROLER看起來像這樣:

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沒有嵌套

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)輪PARAMS應該被嵌套獨輪車內是這樣的:

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

缺少什麼我在這裏?

回答

0

這是你如何生成嵌套字段:

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

好斑點!現在就像一個魅力! – jjabba 2013-02-28 00:19:49