【问题标题】:Rails finding all items in a joins that comply with multiple conditionsRails 在符合多个条件的连接中查找所有项目
【发布时间】:2020-11-06 14:33:02
【问题描述】:

我有VenueReviewVoucher 模型。一个场地has_many 评论和评论has_one 凭证。

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

我正在尝试构建一个查询以选择某个日期之前的所有 claimed: true 凭证,并返回该查询的长度。

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

# @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 的查询时,我得到一个&lt;Review::ActiveRecord_AssociationRelation&gt;

【问题讨论】:

  • “返回该查询的长度”是什么意思?您是否尝试获取记录数?如果是这样,请将length 替换为count
  • @Benj 我也试过用length 代替count,但我得到了同样的StatementInvalid 错误
  • 这里的实际错误信息是什么?请提供一个实际可重现的模型示例,让我们真正开始减少潜在原因。

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

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

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

现在,如果您想针对特定场所进行查询,您仍然希望以 voucher 开始查询,然后将场所表加入其中:

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

【讨论】:

  • 一个更客观的评论会做到这一点,马克斯。我写了这个答案是因为我不知道更好(或者那天太早了)。一旦您提供答案,很高兴向您学习!
猜你喜欢
  • 1970-01-01
  • 2022-11-27
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多