Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to bypass mass assignment protection?

Tags:

I have a Rails 3 app which JSON encodes objects in order to store them in a Redis key/value store.

When I retrieve the objects, I'm trying to decode the JSON and instantiate them from the data like so:

def decode(json)   self.new(ActiveSupport::JSON.decode(json)["#{self.name.downcase}"]) end 

The problem is that doing this involves mass assignment which is disallowed (for good reason I'm told!) for attributes I haven't given attr_writer ability to.

Is there a way I can bypass the mass assignment protection just for this operation only?

like image 598
David Tuite Avatar asked Apr 14 '11 07:04

David Tuite


2 Answers

assign_attributes with without_protection: true seems less intrusive:

user = User.new user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true) user.name       # => "Josh" user.is_admin?  # => true 

@tovodeverett mentioned in the comment you can also use it with new, like this in 1 line

user = User.new({ :name => 'Josh', :is_admin => true }, :without_protection => true) 
like image 187
kizzx2 Avatar answered Oct 13 '22 00:10

kizzx2


EDIT: kizzx2's Answer is a much better solution.

Kind of a hack, but...

self.new do |n|   n.send "attributes=", JSON.decode( json )["#{self.name.downcase}"], false end 

This invokes attributes= passing false for the guard_protected_attributes parameter which will skip any mass assignment checks.

like image 26
Paul Alexander Avatar answered Oct 12 '22 22:10

Paul Alexander