我有兩個模型,Car
和Manufacturer
。這些模型很簡單:Rails - 嵌套模型:不能批量分配受保護的屬性
class Car < ActiveRecord::Base
attr_accessible :manufacturer_id, :car_name, :descr, ...
belongs_to :manufacturer
...
end
和
class Manufacturer < ActiveRecord::Base
attr_accessible :name, :url
has_many :cars
...
end
與表單輸入數據的視圖(views/cars/_form.html.haml
):
= form_for @car do |f|
.field
= f.label :car_name
= f.text_field :car_name
...
= f.fields_for @manufacturer do |m|
.field
= m.label :name
= m.text_field :name
...
當我發送的形式保存輸入的信息(這去CarsController
),我得到這個錯誤:
Can't mass-assign protected attributes: manufacturer
我已經盡力了
accepts_nested_attributes_for :manufacturer
添加到Car
模型,但它並沒有幫助我......
問題出在哪裏?
編輯: 如何我在控制器中保存數據:
@manufacturer = Manufacturer.new(params[:car][:manufacturer])
@car = @manufacturer.cars.build(params[:car])
EDIT2:從日誌 數據:
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"4vcF5NV8D91DkxpCsqCzfbf05sOYsm7ssxZvPa3+kXo=",
"car"=>{"car_name"=>"...",
"descr"=>"...",
"categroy_ids"=>["2",
"3",
"4"],
"manufacturer"=>{"name"=>"Company",
"url"=>"..."}},
"commit"=>"Save",
"id"=>"..."}
謝謝
你的'params [:car]'包含'製造商'屬性..試試這個:'@manufacturer = Manufacturer.new(params [:car] .delete(:manufacturer)); @car = @ manufacturer.cars.build(params [:car])' – codeit 2013-03-27 16:51:55
雖然@codeit是現貨,但您可能需要查看'acceptersted_attributes'。 – Matt 2013-03-27 16:56:29
codeit - 謝謝,但 - 如何更新'更新'行動?保存一個新項目運行良好,但在更新數據時得到相同的錯誤... – user984621 2013-03-27 17:24:06