有没有办法绕过批量分配保护?

| 我有一个Rails 3应用程序,该应用程序使用JSON编码对象,以便将它们存储在Redis键/值存储中。 检索对象时,我正在尝试解码JSON并从数据中实例化它们,如下所示:
def decode(json)
  self.new(ActiveSupport::JSON.decode(json)[\"#{self.name.downcase}\"])
end
问题在于,这样做涉及大量分配,这是我没有赋予attr_writer能力的属性所不允许的(有充分的理由告诉我!)。 有没有一种方法可以仅针对此操作绕过批量分配保护?     
已邀请:
assign_attributes
without_protection: true
似乎不那么令人讨厌:
user = User.new
user.assign_attributes({ :name => \'Josh\', :is_admin => true }, :without_protection => true)
user.name       # => \"Josh\"
user.is_admin?  # => true
评论中提到的@tovodeverett,您也可以将其与ѭ4use一起使用,例如1行
user = User.new({ :name => \'Josh\', :is_admin => true }, :without_protection => true)
    
编辑:kizzx2的答案是一个更好的解决方案。 有点骇客,但是...
self.new do |n|
  n.send \"attributes=\", JSON.decode( json )[\"#{self.name.downcase}\"], false
end
这将为guard_protected_attributes参数调用attribute =传递false,这将跳过所有质量分配检查。     
您也可以以这种方式创建不执行批量分配的用户。
User.create do |user|
  user.name = \"Josh\"
end
您可能需要将此方法放入方法中。
new_user(name)
  User.create do |user|
    user.name = name
  end
end
    

要回复问题请先登录注册