While Rails does a lot to secure your app, some things it leaves to you (as one size doesn’t fit all) and mass assignment security (MAS) is one such example. Rails does of course, make it easy for you to bolt things up, here’s how.
When will you need MAS?
Whenever you are accepting data from users, such as from a form via a params[:hash] and using update_attributes (and family) eg:
@post = Post.new(params[:post])
# do something
# do something else
Why do you need MAS?
Because a hacker can easily get their browser (or use other tools such as curl) to send whatever parameters they want to your site mimicking your form – so you need to tell Rails which attributes should be ‘accessible’. If you don’t, and say your User model/table has a boolean field for admin, then someone could just set themselves as admin.
How do you switch it on?
Easy, in config/application.rb, just uncomment this line:
Then at the top of each model, set which attributes you want to allow to be accessible:
Then to safely update a protected attribute, you simply set the attribute separately:
Are there any alternatives?
Yes, here’s @DHH’s way of dealing with it:
Which then allows you to allow/disallow what is accessible by the user depending on who they are:
params[:post].slice(:title, :content, :published)
But you only really need that if you have different sets of permissions per user – although I think it’s good practise to get into.
The Rails guides on security: Rails Guides / Security