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

孤人 提交于 2019-12-07 06:27:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!