Rails范围具有多个连接和记录查找

时间:2013-11-02 14:25:58

标签: sql ruby-on-rails scope ruby-on-rails-4

我有Client,Deal和DealType模型。 客户有很多优惠。 Deal属于DealType。 DealType有属性 - 关闭。 我需要选择尚未完成交易的所有客户。

scope :active, -> { where('deals.last.deal_type.closing = ?', false) }这样的东西(当然,它不正确)。

如何在Rails 4中以最佳方式完成?

PS。非常感谢有关使用rails了解sql查询的源代码链接。

2 个答案:

答案 0 :(得分:1)

尝试

joins(deals: :deal_type).where('deal_types.closing = ?', false)

好读:

ActiveRecord Query Interface

特别是:

Joining Tables

答案 1 :(得分:-1)

如果您不介意在原始SQL中执行此操作,请尝试:

SELECT clients.*,deals.* FROM clients INNER JOIN deals ON clients.id=deals.client_id
INNER JOIN
(
 SELECT deals.client_id, MAX(deals.created_at) AS latest_deals_date
 FROM deals
 GROUP BY deals.client_id
) latest_deals
ON (deals.client_id=latest_deals.client_id AND deals.created_at>=latest_deals.latest_deals_date)
INNER JOIN deal_types ON deals.deal_type_id=deal_types.id
WHERE deal_types.closing=false;