10

I have a model offers and another historical_offers, one offer has_many historical_offers.

Now I would like to eager load the historical_offers of one given day for a set of offers, if it exists. For this, I think I need to pass the day to the ON clause, not the WHERE clause, so that I get all offers, also when there is no historical_offer for the given day.

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

I would get

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

But I want to have the condition in the ON clause, not in the WHERE clause:

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

I guess I could alter the has_many definition with a lambda condition for a specific date, but how would I pass in a date then?

Alternatively I could write the joins mysqlf like this:

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

But how can I hook this up so that eager loading is done?

4

1 回答 1

1

经过几个小时的头疼并尝试各种方法来完成急切加载一组受限的关联记录后,我在这个线程中遇到了@dbenhur 的答案,这对我来说很好 - 但是条件不是我传递的东西(它是相对于 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])
于 2013-09-01T16:49:06.427 回答