【问题标题】:How to transform sort_by with conditions into a rails scope如何将带有条件的 sort_by 转换为 rails 范围
【发布时间】:2014-04-02 17:31:16
【问题描述】:

我正在尝试更改 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

进入一个范围,因为 self.rank(courses) 返回一个数组而不是一个 activerecord 范围。

当前进度(将更新直到完成):

范围:排名,-> { order(:list_order) }

可能的资源:

【问题讨论】:

    标签: sql ruby-on-rails activerecord ruby-on-rails-4


    【解决方案1】:
     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) } 
    

    像这样使用:

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

    我认为这应该可行?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多