Limit “each” list in Rails

前端 未结 3 1474
借酒劲吻你
借酒劲吻你 2021-02-05 11:42

We have this:

<% @shops.each do |shop| %>
  
  • <%= shop.name %>
  • <% end %>

    The code will yield the total res

    相关标签:
    3条回答
    • 2021-02-05 11:48

      Change the code in your controller where @shops is being set, or change the above code to @shops.take(20).each.

      0 讨论(0)
    • 2021-02-05 12:00

      Just limit it on your ActiveRecord level (or SQL)

      @shops = Shop.limit(20)        # Rails 3+
      @shops = Shop.all :limit => 10 # Rails 2+
      

      Or use Ruby

      <% @shops[0,20].each do |shop| %>
        <li><%= shop.name %></li>
      <% end %>
      
      0 讨论(0)
    • 2021-02-05 12:02

      I would highly suggest using your database to limit the results. This is much more efficient in that your database is doing the work(it is designed to do this) AND you aren't retrieving all your results then filtering them. Imagine if you had 1 million results that you asked your database for... not very desirable.

      You'd want to do:

      Shop.limit(20)
      

      Which has the database doing the work rather than Ruby.

      A quick benchmark test (Comments table only contains 487 results!):

      ruby-1.9.2-p136 :033 > Benchmark.ms do
      ruby-1.9.2-p136 :034 >     Comment.all.take(20)
      ruby-1.9.2-p136 :035?>   end
       => 649.461030960083 
      ruby-1.9.2-p136 :036 > Benchmark.ms do
      ruby-1.9.2-p136 :037 >     Comment.limit(20)
      ruby-1.9.2-p136 :038?>   end
       => 0.1506805419921875 
      

      ~4,300 times worse!

      Or even if your argument is that you have a small amount of results returned, here is another benchmark:

      ruby-1.9.2-p136 :041 > Benchmark.ms do
      ruby-1.9.2-p136 :042 >     Comment.limit(50).take(20)
      ruby-1.9.2-p136 :043?>   end
       => 410.9840393066406 
      ruby-1.9.2-p136 :044 > Benchmark.ms do
      ruby-1.9.2-p136 :045 >     Comment.limit(20)
      ruby-1.9.2-p136 :046?>   end
       => 0.05412101745605469 
      
      0 讨论(0)
    提交回复
    热议问题