【问题标题】:How to write named scope for Audits which don`t have auditables?如何为没有可审计的审计编写命名范围?
【发布时间】:2018-09-18 12:47:21
【问题描述】:

我在我的 Ruby on Rails 应用程序中使用 Audit gem。我在 Audits 和我的Orders 之间使用了多态关联。

现在,我想编写一个命名范围以仅获取未删除订单的审计(发生这种情况是因为订单在创建审计后被删除

<Audit id:110,
auditable_id:4,
auditable_type:"Order",
user_id:1,
user_type:"User",
username:nil,
action:"create",
created_at:"2018-04-07 09:06:20">,
#<Audit id:49,
auditable_id:3,
auditable_type:"Order",
user_id:3,
user_type:"User",
username:nil,
action:"create",
created_at:"2018-04-06 12:28:41">

现在,当我在控制台中输入 Audit.first.auditable 时,我得到 nil,因为与该 Audit 对应的订单被删除,当我输入 Audit.second.auditable 时,我得到与第二个 Audit 对应的订单。

我想过滤我的审计,以便删除订单被删除类型的审计(如 Audit.first)

【问题讨论】:

  • I want to write a named scope to get only those Audits for which Order is not nil 。你的意思是没有删除订单而不是nil?
  • 是的,我的意思是订单没有被删除
  • 应该就像在这里做一个内部连接一样简单。

标签: ruby-on-rails json ruby-on-rails-3 audit named-scope


【解决方案1】:

你可以这样做:

Audit.rb

scope :with_active_orders, -> { joins(:order) }

如果至少有一个Order,它将返回Audits

【讨论】:

  • 你的意思是范围 :with_active_orders, ->{joins(:orders)} 吗?然后我也收到错误 - ActiveRecord::ConfigurationError Exception: Can't join 'Audit' to association named 'order';也许你拼错了?
  • 是的;对不起。如果您使用default_scope,上面的代码将起作用,但对于常规范围,它应该是您拥有它的方式。你得到的错误取决于你如何定义你的关联。尝试order 单数而不是orders 复数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 2012-09-16
  • 1970-01-01
  • 2010-12-15
  • 2022-06-30
  • 2015-12-14
  • 2012-12-19
相关资源
最近更新 更多