How to Bypass attr_accessible and attr_protected in Rails
Posted on 25 Jun 2008Mass assignment in Rails is super handy and saves heaps of code, especially in your controllers. As everyone knows however, hackers love mass assignment so you really need to use attr_accessible or attr_protected to protect your models.
But what happens if you want to mass assign model attributes which are otherwise protected? It would be simple enough to create your own method to do this, but if you take a look at the source you'll see that Rails already has it covered. Here's the method signature for ActiveRecord::Base#attributes=:
def attributes=(new_attributes, guard_protected_attributes = true)
That optional second parameter lets you bypass attr_accessible and attr_protected exactly as we'd like. But how do we call this? Well, you use send.
@model.send :attributes=, attributes, false
