Is there a way to bypass mass assignment protection?

前端 未结 3 1292
余生分开走
余生分开走 2020-12-28 16:46

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 in

相关标签:
3条回答
  • 2020-12-28 16:53

    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.

    0 讨论(0)
  • 2020-12-28 17:01

    You can create a user also in this way which is not doing the mass assignment.

    User.create do |user|
      user.name = "Josh"
    end
    

    You may want to put this into a method.

    new_user(name)
      User.create do |user|
        user.name = name
      end
    end
    
    0 讨论(0)
  • 2020-12-28 17:13

    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)
    
    0 讨论(0)
提交回复
热议问题