Reputation: 5
I'm getting a "ActiveModel::ForbiddenAttributesError in CommentsController#create" with highlights in "@comment = @post.comments.build(params[:comment])"
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
in the tutorial video the coder puts this in and works perfect yet when I post this it gives an error. I have checked through the code and cannot to seem to see whats wrong. Thanks in advance!
Upvotes: 0
Views: 813
Reputation: 53038
Looking at the error, I am assuming that you must be using Rails 4. Strong Parameters were introduced in Rails 4. See Strong Parameters reference here.
Replace
@comment = @post.comments.build(params[:comment])
with
@comment = @post.comments.build(comment_params)
Add a private method in your controller as follows:
def comment_params
params.require(:comment).permit(:attr1, :attr2,...)
end
where :attr1, :attr2 would be the attributes name of Comment model.
Upvotes: 2