我怎么能这样做? on rails活动记录

时间:2017-10-31 08:52:07

标签: ruby-on-rails ruby activerecord

我想在rails active record中实现类似的功能。

SELECT * 
FROM tires 
JOIN comparison_prices 
WHERE comparison_prices.simple_tire_price < tires.web_price 
  AND comparison_prices.simple_tire_price >= tires.web_price - 5

目前我有这样的事情:

@tires = Tire.all
@tires = @tires.joins(:comparison_price).where('tires.web_price > 0')
@tires = @tires.paginate(page: params[:page], per_page: 10).order(:id)

1 个答案:

答案 0 :(得分:0)

因为您的Tire模型has_one :comparison_price可以写:

@tires = Tire.joins(:comparison_price)
             .where('comparison_prices.simple_tire_price < tires.web_price')
             .where('comparison_prices.simple_tire_price >= tires.web_price - 5')
             .paginate(page: params[:page], per_page: 10).order(:id)

或者:

@tires = Tire.joins(:comparison_price)
             .where('comparison_prices.simple_tire_price BETWEEN tires.web_price - 5 AND tires.web_price')
             .paginate(page: params[:page], per_page: 10).order(:id)