Ruby on Rails中的作用域关联

4
我有一个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,但没有成功。


这可能会对你有所帮助:https://github.com/rails/rails/issues/10615。在Rails 3.x中,当你使用joins时,似乎有一个隐式的只读模式。在Rails 4及以上版本中,似乎已经删除了该模式。但是根据那个问题,readonly(false)是推荐的方式。很奇怪它对你不起作用。 - Derek Hopper
1
对于软删除,https://github.com/rubysherpas/paranoia gem 提供了方便的函数。 - Veeresh Honnaraddi
谢谢,我会查看那个宝石的 :) - MZaragoza
1个回答

5
根据在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版本,则可以通过向find方法传递readonly: false选项来解决(不建议使用):

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接