简体   繁体   中英

Rails mass assignment issue

I know this question has been asked a lot, but the solution usually proposed was to set config.active_record.whitelist_attributes to false. I've tried that, and still get this issue:

Can't mass-assign protected attributes: ingredient_attributes

I have two models: recipe.rb and ingredient.rb . They have a one to many relationship, where each recipe can have many ingredients.

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

You need to pluralize :ingredient in your Recipe class:

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

EDIT:

As I suspected, the issue causing the Can't mass-assign protected attributes: ingredient_attributes error is related to your view .

On line 18, you're invoking a fields_for block for :ingredient , which creates a form for a has_one child relationship. However, since a recipe actually has_many ingredients, you should really be using :ingredients :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM