Domanda

I am on Rails3, I have two model, User, and Post. User has Posts as nested attributes. when I try to save user then I am getting Can't mass-assign protected attributes:.....

È stato utile?

Soluzione 2

if the model definitions are like as follows:

user.rb

class User < ActiveRecord::Base
  attr_accessible  :name, :posts_attributes
  has_many :posts
  accepts_nested_attributes_for :posts
end

post.rb

class Post < ActiveRecord::Base
  attr_accessible :title, :content :user_id
end

then everything should be fine. You can save user with posts as nested attributes.

Here is a sample codes for the beginners :)

https://github.com/railscash/sample_change_user_role

Altri suggerimenti

Try this attr_accessible in your post model

http://railscasts.com/episodes/26-hackers-love-mass-assignment

Mass Assignment is the name Rails gives to the act of constructing your object with a parameters hash. It is "mass assignment" in that you are assigning multiple values to attributes via a single assignment operator.

The following snippets perform mass assignment of the name and topic attribute of the Post model:

Post.new(:name => "John", :topic => "Something")
Post.create(:name => "John", :topic => "Something")
Post.update_attributes(:name => "John", :topic => "Something")

In order for this to work, your model must allow mass assignments for each attribute in the hash you're passing in.

There are two situations in which this will fail:

You have an attr_accessible declaration which does not include :name

You have an attr_protected which does include :name

It recently became the default that attributes had to be manually white-listed via a attr_accessible in order for mass assignment to succeed. Prior to this, the default was for attributes to be assignable unless they were explicitly black-listed attr_protected or any other attribute was white-listed with attr_acessible.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top