Ruby on Rails Active Record查询连接两个表并根据条件进行查询

我有两个表:Transactions和Properties。

我有一个条件可以满足,即不需要联接表。

关于我的交易查询:

  • 在某个月份sales_date所在的行
  • sold_or_leased被“租赁”的地方行

我的下一个条件要求将属性添加到事务中,这样我就可以:

  • 在某个月份transactions.sales_date所在的行
  • 行,其中transactions.sold_or_leased为空AND
  • properties.for_sale为假而properties.for_lease为真的情况下行

基本上,已将一个新列添加到名为sold_or_leased的事务中,其中许多为空。我需要一个额外的查询来覆盖null列。

    #test variables for month
    date = "2019-11-01"
    month = Date.parse date

    # below satisfies my first part
    @testobj = Transaction.where(sold_or_leased: "leased")
      .where("sales_date >= ? AND sales_date < ?",month.beginning_of_month,month.end_of_month).count

但是现在我需要扩展此查询以包括属性并测试属性列

我不确定从这里去哪里

    @testobj = Transaction.joins(:property)
      .where(sold_or_leased: "leased")
      .where("sales_date >= ? AND sales_date < ?",month.end_of_month)
      .or(
        Transaction.where(sold_or_lease: nil)
      ).count

此外,当我添加一个联接然后一个or子句时,我得到一个错误Relation passed to #or must be structurally compatible. Incompatible values: [:joins]

我将分享相关的型号信息:

交易模型:

class Transaction < ApplicationRecord
  belongs_to :user
  belongs_to :property
end 

属性模型:

class Property < ApplicationRecord
  has_one :property_transaction,class_name: 'Transaction',dependent: :destroy
end

在塞巴斯蒂安的帮助下,我有以下内容(仍然会产生结构错误消息):

Transaction.joins(:property)
    .where(sales_date: month.all_month,sold_or_leased: nil,properties: { for_sale: false,for_lease: true })
    .or(
      Transaction.joins(:property)
      .where(sold_or_leased: "leased")
      .where("sales_date >= ? AND sales_date < ?",month.end_of_month)
    )
zxofxop 回答:Ruby on Rails Active Record查询连接两个表并根据条件进行查询

从理论上讲,您应该能够在联接后访问properties表列。

查看您当前的代码以及您需要获得的内容,可以尝试以下方法:

Transaction
  .joins(:property)
  .where(sales_date: month.all_month)
  .where(
    "(sold_or_leased IS NULL AND properties.for_sale = false AND properties.for_lease = true) OR
     (sold_or_leased = 'leased')"
  )

如果无法使用ActiveRecord::QueryMethods#or,则可以始终在OR的字符串参数中使用SQL where运算符。

通知month.all_month产生对应月份的整个日期范围,当与where一起使用时,该日期范围将转换为该月的第一天和最后一天:

SELECT ... WHERE "transactions"."sales_date" BETWEEN $1 AND $2 AND ... [["sales_date","2019-11-01"],["sales_date","2019-11-30"]]

month.beginning_of_monthmonth.end_of_month变体短。

本文链接:https://www.f2er.com/3131557.html

大家都在问