如何使用rails3创建范围以获取最后十个事务

Oli*_*ier 5 scope ruby-on-rails-3

尝试将范围添加到我的事务模型以返回created_at的最后10个事务

idl*_*ers 16

scope :most_recent, order(created_at: :desc).limit(10)
Run Code Online (Sandbox Code Playgroud)

  • 范围很难看?哈哈.不像班级方法那么难看 (3认同)

sca*_*er2 13

使用范围

# 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) }
Run Code Online (Sandbox Code Playgroud)

用法示例:

<% Organization.recent(10).each do |organization| %>
  <li><% link_to organization.name, organization %></li>
<% end %>
Run Code Online (Sandbox Code Playgroud)