gpt4 book ai didi

ruby-on-rails - 有没有办法绕过批量分配保护?

转载 作者:数据小太阳 更新时间:2023-10-29 06:28:40 24 4
gpt4 key购买 nike

我有一个 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)

关于ruby-on-rails - 有没有办法绕过批量分配保护?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com