# 基于计算值对 Rails 资源进行排序

·  阅读 538

### 问题

``````Reminder.order('days_until_due ASC')

### 解决方案

##### Step 1：创建实例方法来计算值

``````def days_until_due
today = Time.now
simple_today = Time.new(today.year, today.month, today.day)
if day >= today.day
month_due = today.month
else
month_due = today.month + 1
end
day_due = Time.new(today.year,month_due,day)
return ((day_due - simple_today)/(60*60*24)).to_i
end

##### Step 2：创建一个类方法来查询和排序模型

``````def self.sorted_by_days_until_due
Reminder.all.sort_by(&:days_until_due)
end

``````Reminder.all.class # => Array

``````array = ["Michael", "Adam", "Jen"]

array.sort_by{|word| word.length} # => ["Jen", "Adam", "Michael"]

array.sort_by # => #<Enumerator: ["Michael", "Adam", "Jen"]:sort_by>

``````array = ["Michael", "Adam", "Jen"]

# Passing in a block directly
array.sort_by{|word| word.length} # => ["Jen", "Adam", "Michael"]

# Creating a proc and converting the block to a proc using the '&' syntax
proc = :length.to_proc # => #<Proc:0x007f98a225f700>
array.sort_by(&proc) # => ["Jen", "Adam", "Michael"]

# Creating a proc and converting the block to a proc in one step
array.sort_by(&:length) # => ["Jen", "Adam", "Michael"]

``````def self.sorted_by_days_until_due
Reminder.all.sort_by(&:days_until_due)
end

``````@reminders = Reminder.sorted_by_days_until_due