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

我有一个Rails 3应用程序,JSON对对象进行编码,以便将它们存储在Redis键/值存储中。

当我检索对象时,我正在尝试解码JSON并从数据中实例化它们,如下所示:

def decode(json) self.new(ActiveSupport::JSON.decode(json)["#{self.name.downcase}"]) end 

问题是,这样做涉及质量分配,这是不允许attr_writer能力的属性被禁止的(我有充分理由告诉我!)。

有没有办法可以绕过仅用于此操作的质量分配保护?

assign_attributes with 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在评论中提到你也可以用它来new ,比如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参数调用attributes =传递false,这将跳过任何质量分配检查。

您也可以通过这种方式创建用户,而不是进行批量分配。

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

您可能希望将其放入方法中。

 new_user(name) User.create do |user| user.name = name end end