gpt4 book ai didi

ruby-on-rails - 与 Ruby on Rails 中的范围关联

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:45 26 4
gpt4 key购买 nike

我有一个 Ruby on Rails 应用程序,其中我有许可证、可以许可的项目和一个列出这两者的表格(许可证中有哪些项目?)。类似于购物车中的元素。

有些元素将不再销售,但我打算将它们保存在数据库中。然后,我创建了一个软删除,并为模板和关系使用了默认范围。但是当我尝试使用相关模板更改现有记录时,出现异常:ActiveRecord::ReadOnlyRecord

我的模板是这样的:

class Item <ActiveRecord :: Base
default_scope {where (deleted: false)}
end

class LicenseItem <ActiveRecord :: Base
belongs_to: license, touch: true
belongs_to: item
end

class License <ActiveRecord :: Base
has_many: license_items,
-> {joins (: item) .where (items: {deleted: false})},
dependent:: destroy
end

这样:

pry (main)> License.find (0) .license_items [0] .readonly?
=> true

有什么办法可以让这段感情不只是读书?

我已经尝试将 has_many 范围末尾的 readonly (false) 添加到 License 但没有成功。

最佳答案

根据 this thread in GitHub ,这是Rails 4.0的一个bug,在4.0.1版本中已经修复。更新你的 Rails,你可以在你的范围中包含 readonly (false) 并且它会起作用:

class License <ActiveRecord :: Base
has_many: license_items,
-> {joins (: item) .where (items: {deleted: false}). readonly (false)},
dependent:: destroy
end

要更新 Rails 版本,请编辑您的 Gemfile,然后运行bundle update

在后一种情况下,如果无法更新 Rails 版本,可以将 readonly: false 选项传递给find(不推荐)方法:

License.find (1) .license_items.find (1, readonly: false) .update_attributes (amount: 5)

关于ruby-on-rails - 与 Ruby on Rails 中的范围关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47985204/

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