Is there a way to bypass mass assignment protection?

本秂侑毒 提交于 2019-11-30 03:02:56

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)
Paul Alexander

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!