2013-06-11 78 views
0

我知道這個問題已經被問了很多,但通常提出的解決方案是將config.active_record.whitelist_attributes設置爲false。我已經試過了,仍然得到這個 問題:Rails質量分配問題

Can't mass-assign protected attributes: ingredient_attributes

我有兩個型號:recipe.rbingredient.rb。他們有一對多的關係,每個配方可以有很多成分。

recipe.rb

class Recipe < ActiveRecord::Base 
    attr_accessible :description, :name, :yield, :recipe_id 

    has_many :ingredient, :dependent => :destroy 
    accepts_nested_attributes_for :ingredient 
end 

ingredient.rb

class Ingredient < ActiveRecord::Base 
    belongs_to :recipe 
    attr_accessible :ingredient, :listorder, :recipe_id 
end 
+0

出於好奇,你爲什麼宣佈':recipe_id''attr_accessible'在'Recipe'模式? – zeantsoi

+0

我想我已經讀過這是一個解決大規模分配問題的方法,但它沒有起作用,所以我可以把它拿出來。 –

+0

您收到的錯誤消息表示一對一關係,而不是一對多關係。但是,您的模型看起來正確。也許有些東西在處理你的表單時很腥......你可以發佈你的控制器和視圖嗎? – zeantsoi

回答

5

您需要在您的Recipe類變複數:ingredient

class Recipe < ActiveRecord::Base 
    has_many :ingredients, :dependent => :destroy 
    attr_accessible :description, :name, :yield, :recipe_id, :ingredients_attributes 
    accepts_nested_attributes_for :ingredients 
end 

編輯:

正如我懷疑,導致Can't mass-assign protected attributes: ingredient_attributes錯誤的問題與your view有關。

在第18行,您爲:ingredient調用fields_for塊,該塊創建has_one子關係的表單。然而,由於配方中實際has_many成分,你應該真的使用:ingredients

# app/views/recipe/form.html.erb 
<%= f.fields_for :ingredients do |builder|%> # Line 18 in http://codepad.org/hcoG7BFK 
+0

我是否需要複數has_many呢?我得到這個錯誤'沒有發現名稱成分的關聯。它已被定義? –

+0

好的,我已經這樣做了,但質量分配錯誤仍然存​​在? –

+0

顯式聲明'ingredient_attributes'爲'attr_accessible'。查看更新後的答案。 – zeantsoi