2017-04-18 32 views
0

我的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]) 

但这不行。

此查询将在一些相当大的表中运行,因此不急于加载。

回答

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

+0

谢谢,但仍然不会在这里帮助。我已经在查询中使用了原始枚举值,问题仍然是一样的。 – KJF

+0

你可以在这里发布错误日志吗? – Mayank

相关问题