将返回
我的问题:
模型类
class Question < ActiveRecord::Base
attr_accessible :create_date, :last_update_date, :text, :title
end
从控制器内的方法中我想实现这样的东西:
def index
@recent_questions = Question.all.sort {|a, b| a <=> b}
end
我在哪里可以得到从最近到最老的结果Enumerable order by create_date
我应该在类定义中修改什么?
谢谢。
可以使用scope
class Question < ActiveRecord::Base
#...
scope :by_time, order("created_at DESC")
end
# in controller
def index
@recent_questions = Question.by_time
end
也不要在控制器中使用all
,除非你使用Rails 4。all
将返回一个数组,这可能是非常重的,当你有很多数据。
ActiveRecord::Relation
对象,该对象只在需要时运行查询。使用Ruby的sort_by:
@recent_questions.sort_by(&:create_date)