I'm working on a Rails 3.2.2 application which has JSON APIs and I use a CLI client for inserting some data. It works fine except for the Author model. When I try to create a new post (Post belongs_to :author and Author has_many :posts) I get the following error :

<h1>
  ActiveModel::MassAssignmentSecurity::Error in PostsController#create
</h1>
<pre>Can't mass-assign protected attributes: name</pre>

I did lots of researches on the topic but I found no working solution :-(

I use attr_accessible to avoid MassAssignent errors and it works for all others models but not for the "Author" name attribute.

Here is the Author model :

class Author < ActiveRecord::Base
  attr_accessible :name, :email

  extend FriendlyId
  friendly_id :name, use: :slugged

  # some validations

  has_many :posts
  #authlogic
  acts_as_authentic

  # some stuffs
end

Actually, I have disabled whitelist_attributes and it solved my problem but I suppose that it is not the convenient way to do this (and probably not a good idea).

My questions are : Why the attr_accessible does not work here ? And how can I solve the problem without disabling the whitelist ?

Thank you,

Revan

EDIT :

The method which creates the new post :

def create
  @post = Post.new(params[:post])
  @post.author = current_author
  # respond to etc.
end

current_author finds the author using a given API Key.

有帮助吗?

解决方案

I found the solution ! :-)

The problem was that I used acts_as_taggable_on_steroids plugin which does not work on Rails 3.2 ...

Since "Author" is the only model which has a :name attribute, I thought that the problem came from Author ... but the problem was in the Tag model (which is in the acts_as_taggable_on_steroid plugin). Indeed, its :name attribute is not "accessible".

So, I use the acts_as_taggable_on gem (https://github.com/mbleigh/acts-as-taggable-on) which correctly works on Rails 3.x

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top