ActiveRecord: Adding condition to ON clause for includes

前端 未结 1 1197
长发绾君心
长发绾君心 2021-02-20 10:58

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 se

1条回答
  •  萌比男神i
    2021-02-20 11:23

    After a few hours headscratching and trying all sorts of ways to accomplish eager loading of a constrained set of associated records I came across @dbenhur's answer in this thread which works fine for me - however the condition isn't something I'm passing in (it's a date relative to Date.today). Basically it is creating an association with the conditions I wanted to put into the LEFT JOIN ON clause into the has_many condition.

    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]
    

    And then in my controller:

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

    0 讨论(0)
提交回复
热议问题