查找包含一个连接模型但不包含另一个使用活动记录的所有记录

时间:2017-04-18 12:49:39

标签: ruby-on-rails activerecord

我的rails应用程序中有以下架构。

class Campaign < ApplicationRecord
  has_many :businesses
  has_many :clients, through: :businesses
end

class Business < ApplicationRecord
  has_many :clients
  belongs_to :campaign
end

class Client < ApplicationRecord
  has_many :events
  belongs_to :business
end

class Event < ApplicationRecord
  belongs_to :client

  enum category: {
    :processed,
    :delivered,
    :opened
  }
end

我需要一种方法来查找包含已处理和已投放活动类别但已打开类别的广告系列中的所有客户

我天真的做法是:

c = Campaign.first
c.clients.joins(:events).where('events.category' => [0, 1]).where.not('events.category' => [2])

但这不起作用。

此查询将在一些非常大的表中运行,因此不能选择加载。

1 个答案:

答案 0 :(得分:0)

尝试这些因为枚举不能像基本字符串那样正常比较。

c = Campaign.first
c.clients.joins(:events).where.not("events.category = (?)", Event.category[:opened] )

或只是

c = Campaign.first
c.clients.joins(:events).where("events.category = (?)",[ Event.category[:processed], Event.category[:delivered]] )

可以找到更多信息here

您还可以看到https://stackoverflow.com/a/29135693/7046734