【问题标题】:Complicated polymorphic association query复杂的多态关联查询
【发布时间】:2019-07-28 03:38:24
【问题描述】:

我有一个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

并且希望能够在一个日期范围内为:check_ins 提取所有:reviews。例如:

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】:

    是的,你只需要让 ActiveRecord 知道你计划查询 check_ins 表(如果 where 子句看起来像 check_ins: { anything },AR 知道它,即它是 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..)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 2018-10-31
      • 2014-03-13
      • 1970-01-01
      相关资源
      最近更新 更多