sorting - Sort by two columns rails, but prioritize one if a field is nil? -



sorting - Sort by two columns rails, but prioritize one if a field is nil? -

so have table column priority_n. pretend there's 5 items in table. 2 nil priority_n, , other 3 have 1, 2, 3 in priority_n.

so i'd where(priority_n: nil).order(published_at: :desc) combined where.not(priority_n: nil).order(priority_n: :asc). want nil ones @ origin of active record relations, , prioritized ones after them. there way this?

i think trick:

class mymodel scope :with_priority, -> { where.not(priority: nil).reorder(:priority) } scope :without_priority, -> { where(priority: nil).reorder(published_at: :desc) } def self.special_order without_priority.to_a + with_priority.to_a end end

now, can call: mymodel.special_order returns array ordered ask.

ruby-on-rails sorting activerecord

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -