Shane
Shane

Reputation: 5687

Mass Assignment issue in rails

I was going through this article below. http://tutorials.jumpstartlab.com/projects/blogger.html#i2:-adding-comments

Below is the code where we create a new Comment object and associate with corresponding article.

@comment = Comment.new
@comment.article_id = @article.id

Can anyone explain me what the author is trying to say below. Can anyone show me how to do otherwise without the security thing for better understanding.

Due to the Rails’ mass-assignment protection, the article_id attribute of the new Comment object needs to be manually assigned with the id of the Article.

Upvotes: 0

Views: 90

Answers (1)

BroiSatse
BroiSatse

Reputation: 44725

The article you were reading was referring to rails 3. Rails 3 doesn't use strong parameters like Rails 4 and instead uses attr_accessible with a list of attributes which are permitted to be mass assigned.

Mass assignment in ruby is everything where you use a hash to set multiple variables at once in methods like new, create or assign_attributes. Quite often it is not a good idea to allow mass assignment of foreign keys.

In summary, author meant that those two lines cannot be written as:

@comment = Comment.new(article_id: @article.id)

since article_id is not listed in attr_accessible and it will raise Mass Assignment security exception.

Upvotes: 2

Related Questions