0

I'm getting an error when sending a post request to my comments controller using form_for([@post, @comment]). To create a comment.

ActiveModel::ForbiddenAttributesError in CommentsController#create

Line causing the error:

@comment = @post.comments.build(params[:comment])

I know that it is down to a strong parameters issue but I can't seem to get it right. At the moment my model for posts is:

posts.rb

class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy
end

And for comments:

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :post
end

My current strong parameters setup for the comments controller is:

comments_controller.rb

  private

    def comment_params
      params.require(:post).permit(comment: [:name, :body])
    end

And finally parameters as being reported by the error message are:

{"utf8"=>"✓",
 "authenticity_token"=>"MSX1PrrvfzYBr/DNYaMgSw3opWmaJs82xd11JfLPIqI=",
 "comment"=>{"name"=>"",
 "body"=>""},
 "commit"=>"Create Comment",
 "post_id"=>"1"}

Anyone got any ideas where my strong params setup is broken - any ideas would be greatly appreciated. Thanks!

2 Answers 2

2

In your controller you're requiring your post, not your comment. Maybe try:

def comment_params
  params.require(:comment).permit(:name, :body)
end

then do:

@comment = @post.comments.build(comment_params)

See if that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer it's appreciated. Are there any guides or docs you would recommend I read around nested parameters?
Sure, check out the github page here: github.com/rails/strong_parameters.
1

A couple of problems...

One problem is that you aren't using your comment_params in the build method...

@comment = @post.comments.build(params[:comment])

should be

@comment = @post.comments.build(comment_params[:comment])

But we have another issue in that your sent params actually is not {post: {comment: 'stuff here'}} like your comment_params method indicates. It's actually {comment: 'stuff here'}

So you should change comment params:

def comment_params
  params.require(:comment).permit(:name, :body)
end

And then to build your comment:

@comment = @post.comments.build(comment_params)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.