我有两个表: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)
)