ActiveModel::ForbiddenAttributesError in BlogPostsController#comments

June 24, 2014

WTF

So today while going through the legendary “Create a Blog with Rails” tutorial I got this fantastic error message:

1
ActiveModel::ForbiddenAttributesError

Okay, so some or other attributes are forbidden well thanks that is informative. So this helped a bit though at least I knew what line was giving me an error.

1
2
3
# POST /comment
  def comment
    @comment = Comment.new(params[:comment]) #Error is here

ActiveModel::ForbiddenAttributesError in BlogPostsController#comments

So I obviously googled this and got to this StackOverflow answer

I guess you are using Rails 4. If so, the needed parameters must be marked as required.

1
2
3
4
 
def user_params
    params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
  end

So all I needed was to add this

1
2
3
def comment_params
      params.require(:comment).permit(:email, :comment, :blog_post_id)
end

and change my comment method to

1
2
3
# POST /comment
  def comment
    @comment = Comment.new(comment_params)

I struggled with this for a while and looking back I feel like an idiot that the fix was so easy o_O.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus