Rails - attr_accessible & mass assign

I have a question about using attr_accessiblein Rails.

I sometimes want to set guard_protected_attributesto falseto get around the mass assignment protection. I am wondering why the following line does not work (it creates the error "can not stringify keys"):

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

... but it does:

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

Does anyone know the reason?

+3
source share
4 answers

Because the Ruby parser parses ' { :name => "James Bond", :admin => true}, false' as the only argument #attributes=. Method call ' foo=' limits you to one argument in Ruby. sendcircumvents this.

, , Rails false, , FalseClass, Hash, .

+6

, , , , .send ?

+1

I just defined some helper methods to make it easier to bypass the constraints of mass assignment.

module ActiveRecord
  class Base

    # Assigns attributes while ignoring mass assignment protection
    def force_feed(attributes)
      self.send(:attributes=, attributes, false)
      self
    end

  end
end
+1
source

In later versions of ActiveRecord, the second parameter was displayed for the = attributes. Now you can trigger the same effect:

model.assign_attributes(attributes, :without_protection => true)
+1
source

Source: https://habr.com/ru/post/1709790/


All Articles