简体   繁体   English

复杂多态关联查询

[英]Complicated polymorphic association query

I have a Review model and a CheckIn model: 我有一个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

And would like to be able to pull in all :reviews for :check_ins within a date range. 并希望能够提取日期范围内:check_ins所有:reviews 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. 理想情况下,我想要一个ActiveRecord::Relation而不是一个数组。

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 } , ie it's a Hash , but doesn't know it if it's String , like here), so it did left join , like this: 是的,您只需要让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)

or with eager_load : 或使用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 :)): 另外,如果您使用的是Ruby 2.6,则可能可以使用无限范围,但是我不确定它是否可以工作(尽管我很高兴它看起来很酷:)):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM