【问题标题】:ActiveRecord: Adding condition to ON clause for includesActiveRecord:为包含的 ON 子句添加条件
【发布时间】:2012-11-09 11:59:58
【问题描述】:

我有一个模型报价和另一个历史报价,一个报价有_许多历史报价。

现在我想急切地加载某一天的history_offers 以获取一组优惠(如果存​​在)。为此,我认为我需要将这一天传递给 ON 子句,而不是 WHERE 子句,这样我才能获得所有报价,即使在给定日期没有 history_offer 时也是如此。

有 Offer.where(several_complex_conditions).includes(:historical_offers).where("historical_offers.day = ?", Date.today)

我会得到

SELECT * FROM offers 
LEFT OUTER JOIN historical_offers 
ON offers.id = historical_offers.offer_id 
WHERE day = '2012-11-09' AND ...

但我想在 ON 子句中添加条件,而不是在 WHERE 子句中:

SELECT * FROM offers 
LEFT OUTER JOIN historical_offers 
ON offers.id = historical_offers.offer_id AND day = '2012-11-09' 
WHERE ...

我想我可以使用特定日期的 lambda 条件更改 has_many 定义,但是我将如何传递日期?

或者,我可以像这样编写连接 mysqlf:

Offer.where(several_complex_conditions)
  .joins(["historical_offers ON offers.id = historical_offers.offer_id AND day = ?", Date.today])

但是我怎样才能把它连接起来以便完成预加载呢?

【问题讨论】:

  • A related question 受到了更多关注,但没有人给出您正在寻找的内容。

标签: ruby-on-rails-3 activerecord join


【解决方案1】:

经过几个小时的头疼并尝试各种方法来完成急切加载一组受限的关联记录,我遇到了@dbenhur 的answer in this thread,这对我来说很好 - 但是条件不是我正在传递的东西in(它是相对于 Date.today 的日期)。基本上它是与我想将 LEFT JOIN ON 子句放入 has_many 条件的条件创建关联。

has_many :prices, order: "rate_date"
has_many :future_valid_prices,
    class_name: 'Price',
    conditions: ['rate_date > ? and rate is not null', Date.today-7.days]

然后在我的控制器中:

@property = current_agent.properties.includes(:future_valid_prices).find_by_id(params[:id])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多