0

我知道这个问题被问了很多,但通常提出的解决方案是设置config.active_record.whitelist_attributes为 false。我已经尝试过了,但仍然遇到这个问题:

Can't mass-assign protected attributes: ingredient_attributes

我有两个模型:recipe.rbingredients.rb。他们有一对多的关系,每个食谱可以有很多成分。

食谱.rb

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

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

成分.rb

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

1 回答 1

5

你需要:ingredientRecipe课堂上复数:

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错误的问题与您的观点有关。

在第 18 行,您正在调用一个fields_for块 for ,它为子关系:ingredient创建一个表单。has_one但是,由于食谱实际上是has_many成分,因此您应该真正使用:ingredients

# app/views/recipe/form.html.erb
<%= f.fields_for :ingredients do |builder|%> # Line 18 in http://codepad.org/hcoG7BFK
于 2013-06-11T17:48:20.757 回答