Activerecord查询以基于关联属性获取集合

时间:2017-02-27 21:11:34

标签: ruby-on-rails ruby

我有以下关联:

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_collat​​eral为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'

1 个答案:

答案 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