没有 SQL?我想到了两个选择。创建一个哈希数组并在那里对其进行排序,或者在数据库中添加另一列并对其进行排序。
# How many records in the meetings table? This array of hashes could get huge.
meetings_array = []
Meeting.all.each do |meeting|
meetings_array << {id: meeting.id, started_at: meeting.started_at, ended_at: meeting.ended_at , duration: meeting.ended_at - meeting.started_at }
end
meetings_array.sort_by { |hsh| hsh[:duration] }
或者,创建另一列:
# Is it worth adding another column?
create_table :meetings do |t|
t.datetime :started_at
t.datetime :ended_at
t.datetime :duration
end
每当您同时拥有started_at
和时更新此列ended_at
。那么你也能:
Meeting.order("duration")