2013-06-11 77 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