具有嵌套关联且包含的Active Record查询

问题描述 投票:0回答:1

我正在使用一个预订系统,该系统允许所有者在某些属性上禁止某些日期。因此,要生成特定日期所有属性的可用性,我需要首先查看该日期是否有任何property_blackout_dates。

class PropertyBlackoutDate < ApplicationRecord
  belongs_to :property
end 

class Property < ApplicationRecord
  has_many :property_blackout_dates
end 

因为我希望所有的属性都没有指定日期的property_blackout_date,所以我尝试这样做:

date = "2020-02-22"
Property.includes(:property_blackout_dates).where.not(property_blackout_dates: {date: date}).references(:property_blackout_dates

但是即使我有Properties和PropertyBlackoutDates,它也只是返回一个空对象。

我在做什么错?

ruby-on-rails activerecord rails-activerecord
1个回答
0
投票

对于这样的事情,我可能会使用嵌套查询:

Property.where.not(id: Property.select(:id).joins(:property_blackout_dates).where(property_blackout_dates: {date: date}))

未经测试,但应在一个查询中执行。

您也可以使其成为清理范围。

class Property < ActiveModel::Base
  # Example: Property.not_blacked_out(date)
  scope :not_blacked_out, ->(date) { where.not(id: select(:id).joins(:property_blackout_dates).where(property_blackout_dates: {date: date})) } 
end
© www.soinside.com 2019 - 2024. All rights reserved.