Tom
Tom

Reputation: 480

Strong Parameters and Nested Parameters - Rails 4

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!

Upvotes: 0

Views: 136

Answers (2)

nzifnab
nzifnab

Reputation: 16120

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)

Upvotes: 1

jklina
jklina

Reputation: 3417

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.

Upvotes: 2

Related Questions