Rails 查找联接中符合多个条件的所有项目

Rails finding all items in a joins that comply with multiple conditions

我有 VenueReviewVoucher 模型。场地 has_many 评论和评论 has_one 代金券。

凭证有一个布尔值 claimed 字段。

我正在尝试构建一个查询,以 select 特定日期之前的所有 claimed: true 优惠券,以及 return 该查询的长度。

到目前为止,我已经尝试了以下几种查询:

# @venue is an instance of a Venue
@venue.reviews.joins(:voucher)
    .where(vouchers: { claimed: true })
    .where("created_at < ?", Date.today.beginning_of_week - 7)
    .length

但是我只是得到一个模糊的 ActiveRecord::StatementInvalid 错误,我的 .length 被突出显示。当我在控制台中尝试没有 .length 的上述查询时,我得到一个 <Review::ActiveRecord_AssociationRelation>

如果您想要计算声明为真的代金券数量和正确的时间戳,您可以这样做:

Voucher.where(vouchers: { claimed: true })
       .where("created_at < ?", Date.today.beginning_of_week - 7)
       .length

现在,如果您想要针对特定​​地点,您仍然希望从 voucher 开始查询,然后将地点 table 加入其中:

Voucher.joins(review: :venue)
       .where(venue_id: @venue.id)
       .where(vouchers: { claimed: true })
       .where("created_at < ?", Date.today.beginning_of_week - 7)
       .length

您可能需要尝试一下 .joins(review: :venue) 您可以在此处找到更多信息:https://guides.rubyonrails.org/active_record_querying.html#joining-tables