Ruby on rails 如何不使用merge将两个关联连接到一个查询中

Ruby on rails 如何不使用merge将两个关联连接到一个查询中,ruby-on-rails,Ruby On Rails,我正在构建Rails 5.2应用程序 在这个应用程序中,我得到了包含许多事件和会议的项目对象。 事件和会议都有许多日历项 我希望以ActiveRecord关系获取项目的所有日历项。我现在可以通过合并两个查询来实现这一点,但是我得到了一个数组,但是我需要做一些额外的过滤和分页,所以我需要一个真正的ActiveRecord关系 项目 has_many :events has_many :meetings has_many :event_calendar_items, through: :events

我正在构建Rails 5.2应用程序

在这个应用程序中,我得到了包含许多事件和会议的项目对象。 事件和会议都有许多日历项

我希望以ActiveRecord关系获取项目的所有日历项。我现在可以通过合并两个查询来实现这一点,但是我得到了一个数组,但是我需要做一些额外的过滤和分页,所以我需要一个真正的ActiveRecord关系

项目

has_many :events
has_many :meetings
has_many :event_calendar_items, through: :events, source: "calendar_item"
has_many :meeting_calendar_items, through: :meetings, source: "calendar_item"
has_many :calendar_items
会议

has_many :calendar_items
事件

has_many :events
has_many :meetings
has_many :event_calendar_items, through: :events, source: "calendar_item"
has_many :meeting_calendar_items, through: :meetings, source: "calendar_item"
has_many :calendar_items
日历项目

belongs_to :calendar
belongs_to :event
belongs_to :meeting
当我这样做时,它会工作,但会生成一个数组:

event_calendar_items + meeting_calendar_items
Project.joins(:event_calendar_items, :meeting_calendar_items)
这将导致与项目的ActiveRecord关系:

event_calendar_items + meeting_calendar_items
Project.joins(:event_calendar_items, :meeting_calendar_items)
我在项目模型中尝试了这一点,效果很好,但感觉很粗糙(?)


如何创建一个真正的ActiveRecord关系,以便进行更多筛选?某种类型的联接?

作为SQL选择,这类似于:

SELECT * FROM calendar_items
  JOIN events WHERE events.id = calendar_items.event_id
  JOIN meetings WHERE meetings.id = calendar_items.meeting_id
WHERE
  events.project_id = ? OR meetings.project_id = ?
所以我认为你可以这样做:

def calendar_items
  items = CalendarItem.joins(:event, :meeting)
  items.where('events.project_id = ?', self.id).or(items.where('meetings.project_id = ?', self.id))
end

我还没有测试过,所以不确定,但看起来还可以。

作为SQL选择,这将类似于:

SELECT * FROM calendar_items
  JOIN events WHERE events.id = calendar_items.event_id
  JOIN meetings WHERE meetings.id = calendar_items.meeting_id
WHERE
  events.project_id = ? OR meetings.project_id = ?
所以我认为你可以这样做:

def calendar_items
  items = CalendarItem.joins(:event, :meeting)
  items.where('events.project_id = ?', self.id).or(items.where('meetings.project_id = ?', self.id))
end

我还没有测试过,所以不确定,但看起来还可以。

是否有CalendarItem的模型?有哪些关系?已使用CalendarItem关系更新问题。谢谢关于
CalendarItem.join(:事件,:会议)在哪里(事件:{project\u id:id})
?如果您有一个实例化的项目对象。
事件
和/或
会议
应该可以互换工作,因为它们都有一列
项目id
,并且与项目模型相关。是否有日历项的模型?有哪些关系?已使用CalendarItem关系更新问题。谢谢关于
CalendarItem.join(:事件,:会议)在哪里(事件:{project\u id:id})
?如果您有一个实例化的项目对象。
事件
和/或
会议
应该可以互换,因为它们都有一列
项目id
,并且与项目模型相关。谢谢!看起来不错,谢谢!它似乎工作得很好。