我有以下关联:
business belongs_to :loan
business has_many :property_addresses, class_name: 'Address::Property', as: :addressable
Address::Property has a column called as_collateral which holds a boolean.
从我的贷款模型中,我想创建一个范围,该范围返回具有as_collateral为true的property_address的贷款。 (即Loan.with_collateral
)
我尝试了以下查询的几个版本(不同的复数形式),但一直收到错误:
Loan.joins(:business => :property_addresses).where('businesses.property_addresses.as_collateral': true).first
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'businesses.property_addresses.as_collateral'
答案 0 :(得分:3)
使用merge
方法,在您需要交叉查询时非常有用。阅读更多in the docs
Loan.joins(business: :property_addresses)
.merge(PropertyAddress.where(as_collateral: true))
生成的SQL查询将是
SELECT `loans`.* FROM `loans`
INNER JOIN `businesses`
ON `businesses`.`id` = `loans`.`business_id`
INNER JOIN `property_addresses`
ON `property_addresses`.`business_id` = `businesses`.`id`
WHERE `property_addresses`.`as_collateral` = 1