I have a model Trade
that has columns traded_at
, price
, amount
.
And there is a default_order
for it like this.
scope :default_order, -> {
order(traded_at: :desc, price: :asc, amount: :desc)
}
I want to filter the trades
by using this order clause.
This is my code for it without order clause.
scope :newer_than, ->(trade) {
where(<<-SQL)
traded_at > '#{trade.traded_at.to_s(:db)}' OR
(traded_at = '#{trade.traded_at.to_s(:db)}' AND price < #{trade.price}) OR
(traded_at = '#{trade.traded_at.to_s(:db)}' AND price = #{trade.price} AND amount > #{trade.amount})
SQL
}
When I add one more ORDER BY
item, I need to add 4 conditions in WHERE
clause. Etc. The number grows binomially.
I think it's not efficient. Is there a more efficient way to translate multiple ORDER BY
expressions into a matching WHERE
clause?