ruby-on-railsruby-on-rails-3nested-attributesmass-assignmentattr-accessible

Getting "Can't mass-assign protected attributes:" for nested_attributes


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:.....


Solution

  • 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