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
EDIT:
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.
EDIT2: Migration File
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_idkey from params, notarticle_id.instead of
Ruby does not throw undefined error for self-assignment,