复杂的多态关联查询

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

我有一个Review模型和CheckIn模型:

class Review < ApplicationRecord
    belongs_to :reviewable, polymorphic: true
    belongs_to :check_in, -> { where( reviews: { reviewable_type: "CheckIn"} ).includes(:review) }, foreign_key: 'reviewable_id', optional: true   
end

class CheckIn < ApplicationRecord
    has_one :review, as: :reviewable
end

并希望能够在日期范围内为:reviews拉入所有:check_ins。例如:

Review.includes(:check_in).where("check_ins.created_at >= ?", Date.today)

这失败的原因是:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "check_ins"

有没有办法实现这个目标?理想情况下,我想要一个ActiveRecord::Relation而不是阵列。

ruby-on-rails polymorphism associations
1个回答
3
投票

是的,你只需要让ActiveRecord知道你打算查询check_ins表(AR知道如果where子句看起来像check_ins: { anything },即它是Hash,但不知道它是否是String,就像这里),所以它做了left join,像这样:

Review.includes(:check_in).references(:check_ins).where('check_ins.created_at >= ?', Date.today)

或与eager_load

Review.eager_load(:check_in).where('check_ins.created_at >= ?', Date.today)

另外,如果你使用的是Ruby 2.6,它可能会使用无限范围,但我不确定它是否有效(尽管我会很高兴,如果它是,它看起来很酷:) :):

Review.includes(:check_in).where(check_ins: Date.today..)
© www.soinside.com 2019 - 2024. All rights reserved.