How to create a scope to receive the last ten transactions with rails3

Trying to add an area of โ€‹โ€‹my transaction model to return the last 10 transactions by created_at

+5
source share
3 answers
scope :most_recent, order(created_at: :desc).limit(10)
+15
source

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) }

Usage example:

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

If you want to perform this merge operation, you can directly limit the number of records retrieved from the association

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

All Articles