Search code examples
ruby-on-railsrubymass-assignment

Rails - attr_accessible & mass assignment


I have a question about using attr_accessible in Rails.

I sometimes want to set guard_protected_attributes to false in order to bypass mass assignment protection. I'm wondering why the following line doesn't work (it creates the "can't stringify keys" error):

@user.attributes=({ :name => "James Bond", :admin => true }, false)

...but this does:

@user.send(:attributes=, { :name => "James Bond", :admin => true }, false)

Anyone know the reason?


Solution

  • Because the Ruby parser parses '{ :name => "James Bond", :admin => true}, false' as the single argument to #attributes=. Calling a method 'foo=' limits you to one argument in Ruby. The send gets around that.

    What's actually happening is that Rails is trying to stringify the keys of false, which, being a FalseClass rather than a Hash, doesn't have any.