【问题标题】:Association with scope in Ruby on Rails与 Ruby on Rails 中的范围关联
【发布时间】:2017-12-27 01:00:13
【问题描述】:

我有一个 Ruby on Rails 应用程序,其中我有许可证、可以获得许可的项目以及列出这两者的表格(许可证中存在哪些项目的数量?)。类似于购物车中的物品。

有些商品将不再销售,但我打算将它们保存在数据库中。然后我创建了一个 soft-delete 并为模板和关系使用了默认范围。但是当我尝试使用相关模板更改现有记录时,出现异常: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,但没有成功。

【问题讨论】:

  • 这可能会对您有所帮助:github.com/rails/rails/issues/10615。在 Rails 3.x 中,当您使用 joins 时,似乎存在隐式只读。在 Rails 4 及更高版本中,这似乎已被删除。不过根据那个问题,readonly(false) 是推荐的方式。奇怪的是它不适合你。
  • 对于软删除github.com/rubysherpas/paranoia gem 提供了方便的功能。
  • 谢谢,我会研究那个宝石 :)

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


【解决方案1】:

根据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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多