Reputation: 1896
I started playing with Rails 4 last night. And I'm making a simple blog type app to become familiar with some of the changes. I have posts working with the default scaffolding.
I decided to work through adding comments without scaffolding and I'm getting this error when I try to save a comment on a post:
ActiveModel::ForbiddenAttributesError in CommentsController#create
Request Params ON Error Page:
{"utf8"=>"✓",
"authenticity_token"=>"jkald9....",
"comment"=>{"commenter"=>"Sam",
"body"=>"I love this post!"},
"commit"=>"Create Comment",
"post_id"=>"1"}
Here is the comment controller's create action:
class CommentsController < ApplicationController
def create
@post = post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body, :post_id)
end
end
Here's the very basic migration for my comments.
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :post, index: true
t.timestamps
end
end
end
What am I doing wrong with Strongly typed params? Or maybe there is something else that has changed in Rails 4 that I'm missing?
Upvotes: 2
Views: 2274
Reputation: 43
I got around this by editing the comments_controller create function to
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:commenter, :body))
redirect_to post_path(@post)
end
note the
@comment = @post.comments.create(params[:comment].permit(:commenter, :body))
Best Regards
Upvotes: 1
Reputation: 1896
Bit of an oversight,but I figured I would answer this question in case anyone else was working on porting similar Rails 3 code to Rails 4.
You need to pass comment_params into the mass assignment like this:
@comment = @post.comments.create(comment_params)
Upvotes: 4