2011-01-20 55 views

回答

15
scope :most_recent, order(created_at: :desc).limit(10) 
+3

範圍是醜陋的?哈哈。不像班級方法那麼醜陋 – idrinkpabst 2014-03-12 00:37:18

+0

這是怎麼得到upvoted?範圍真的在出路嗎? – 2015-03-09 13:39:01

12

使用範圍

# Ruby 1.8 style 
scope :recent, lambda { |num| order('created_at DESC').limit(num) } 

# Ruby 1.9/2.0 style 
scope :recent, ->(num) { order('created_at DESC').limit(num) } 

例使用方法:

<% Organization.recent(10).each do |organization| %> 
    <li><% link_to organization.name, organization %></li> 
<% end %> 
0

如果您想對關聯進行此操作,您可以直接限制記錄數rds獲取從協會

class School 
has_many :students -> order(created_at: :desc).limit(10) 
end