I'm following a great intro level tutorial to Rails , and it's been a great experience - until I hit this
ActiveModel::MassAssignmentSecurity::Error in CommentsController#create
Can't mass-assign protected attributes: article_id
This is how the CommentsController looks like
class CommentsController < ApplicationController
def create
article_id = params[:comment].delete(article_id)
@comment = Comment.new(params[:comment])
@comment.article_id = article_id
@comment.save
redirect_to(article_path(@comment.article),
:notice => "Comment added by #{@comment.author_name}.")
end
end
According to the tutorial, writing the create method this way instead of just writing like @comment = Comment.new(params[:comment]
and @comment.save
is to avoid Mass-Assignment Security Error. I think this is caused by using a different version of rails because I'm running Rails 3.2.8 and the author of that tutorial was running Rails 3.2.2 as the time of writing.
Could someone please offer me a solution? Thanks
I Googled a bit and found that you can use the :as option to define a role for the class, but I don't really know if I should be using it here. I've just started learning Rails today, and I'm stilling trying to get my head around it after knowing some basics.
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.integer :article_id
t.string :author_name
t.text :body
t.timestamps
end
end
end
You probably need to delete :article_id
key from params, not article_id
.
article_id = params[:comment].delete(:article_id)
instead of
article_id = params[:comment].delete(article_id)
Ruby does not throw undefined error for self-assignment,
a = a
=> nil
b = c
=> NameError
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.