Jeremy Thomas
Jeremy Thomas

Reputation: 6694

Complicated polymorphic association query

I have a Review model and a CheckIn model:

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

And would like to be able to pull in all :reviews for :check_ins within a date range. For example:

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

This fails due to:

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

Is there some way to accomplish this? Ideally I'd like an ActiveRecord::Relation and not an array.

Upvotes: 0

Views: 40

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51191

Yes, you just have to let ActiveRecord know you're planning to query against check_ins table (AR knows it if the where clause looks like check_ins: { anything }, i.e. it's a Hash, but doesn't know it if it's String, like here), so it did left join, like this:

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

or with eager_load:

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

Also, if you're using Ruby 2.6, it might be possible to use infinite range, but I'm not sure it works (though I would be glad if it was, it looks cool :)):

Review.includes(:check_in).where(check_ins: Date.today..)

Upvotes: 3

Related Questions