问题
Trying to add a scope to my transactions model to return the last 10 transactions by created_at
回答1:
scope :most_recent, order(created_at: :desc).limit(10)
回答2:
Use scopes
# 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) }
Example Usage:
<% Organization.recent(10).each do |organization| %>
<li><% link_to organization.name, organization %></li>
<% end %>
回答3:
If you want to do this operation on association you can directly limit the number of records getting retrieved from the association
class School
has_many :students -> order(created_at: :desc).limit(10)
end
来源:https://stackoverflow.com/questions/4744037/how-to-create-a-scope-to-get-the-last-ten-transactions-with-rails3