Rails质量分配问题

时间:2013-06-11 17:46:05

标签: ruby-on-rails ruby ruby-on-rails-3

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

Can't mass-assign protected attributes: ingredient_attributes

我有两个模型: recipe.rb ingredient.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

1 个答案:

答案 0 :(得分:5)

您需要在:ingredient课程中复数Recipe

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行,您正在为fields_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