Rails Mass Assignment Error/Security

When creating a form in Ruby on Rails, you’re offering an end user a way to save data to your database. But that end user could be anyone. It could be someone who is using your site as intended, or, someone who is trying to hack into your system and ruin your life.

Now to save a new object to your database in Ruby on Rails, you will need to run a piece of code with update_attributes like the following:

@book = Book.new({ :title => 'Fellowship of the Ring', :pagecount => 450 })

Running this code will yield the following error:

MassAssignmentSecurity::Error: Can't mass-assign protected attributes.......

This is actually a good thing. Rails has built in security that will not permit potentially malicious code, like the above example, to run unless you tell the model that “title” and “pagecount” can be updated via mass assignment. To do this, you will need to add the following bolded line to the beginning of your model.

class Book < ActiveRecord::Base
 attr_accessible :title, :pagecount

end

Now rails knows that it’s OK to let the Book model’s “title” and “pagecount” atributes be mass assignable, and forms that use the values, or, any code that sets them, will begin to work.

Just be careful, if you don’t need the values to be attr_accessible, don’t set them that way.

Note: in rails versions older than 3.2.3, mass assignment is not be disabled by default, in which case, it’s essential to set which model attributes to “white-list” via attr_accessible, otherwise, all attributes will be mass assignable, which is very bad!

Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: