【问题标题】:Active Record query with nested association and includes具有嵌套关联的 Active Record 查询,包括
【发布时间】:2020-02-22 00:29:20
【问题描述】:

我正在开发一个预订系统,该系统允许业主在某些属性上取消某些日期。因此,要生成特定日期所有属性的可用性,我需要首先查看该日期是否有任何 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】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多