有没有办法绕过批量分配保护? [英] Is there a way to bypass mass assignment protection?

查看:97
本文介绍了有没有办法绕过批量分配保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails 3应用,该应用对JSON进行编码以将对象存储在Redis键/值存储中.

I have a Rails 3 app which JSON encodes objects in order to store them in a Redis key/value store.

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

When I retrieve the objects, I'm trying to decode the JSON and instantiate them from the data like so:

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

问题在于,这样做涉及大量分配,这是我没有赋予attr_writer能力的属性所不允许的(有充分的理由告诉我!).

The problem is that doing this involves mass assignment which is disallowed (for good reason I'm told!) for attributes I haven't given attr_writer ability to.

有没有一种方法可以仅针对此操作绕过批量分配保护?

Is there a way I can bypass the mass assignment protection just for this operation only?

推荐答案

assign_attributeswithout_protection: true似乎不那么令人讨厌:

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,您也可以将其与new一起使用,例如1行

@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)

这篇关于有没有办法绕过批量分配保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆