Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform sort_by with conditions into a rails scope

I'm trying to change self.rank:

def self.rank(courses)
  courses.sort_by do |course|
    [course.list_order ? course.list_order : Float::INFINITY,
     course.upcoming? ? 0 : 1,
     course.title
    ]
  end
end

def upcoming?
  start_date && start_date > Time.now.utc
end

into a scope, as self.rank(courses) returns an array rather than an activerecord scope.

current progress (will update til complete):

scope :ranked, -> { order(:list_order) }

possible resources:

  • Conditional order for nested model based on field
  • SQL Conditional Order By
like image 726
Foolish Chap Avatar asked Jan 25 '26 05:01

Foolish Chap


1 Answers

 scope :just_what_i_want, lambda { |course_id| where(:course_id => course_id) }
 scope :ranked, lambda { |list_order| order(list_order ?  list_order : Float::INFINITY).order('start_date DESC').order(:title) } 

use like:

 Courses.just_what_i_want([1,2,3,4,5,6]).ranked('course_id')

I think this should work?

like image 84
Ben Nelson Avatar answered Jan 26 '26 19:01

Ben Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!