ActiveRecordのModelに include することで簡単にソート順(order)を指定できるようになります。
すごく複雑な条件とかは全然考慮してません。
Railsなら上記の sortable.rb を lib に配置。
ActiveRecordを継承したModelに対して include を行います。
class User < ActiveRecord::Base
include Sortable
end次にソート順を指定します。
class User < ActiveRecord::Base
include Sortable
# 単体キー
sortable :created_at
# 単体キーで別名にしたい場合
sortable :time, :created_at
# 複合キー
sortable :name_kana, [:last_name_kana, :first_name_kana]
end以下のような組み合わせで検索指定が可能。
# ORDER BY created_at DESC
User.sort(:created_at, "down")
# ORDER BY created_at ASC
User.sort(:time, "up")
# ORDER BY last_name_kana DESC, first_name_kana DESC
User.sort(:name_kana, "down")