Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit "each" list in Rails

We have this:

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

The code will yield the total result of 50 entries (in my case).

How can I limit this view to 20? Yeah, just limit it, I don't want any pagination or what.

Thanks.

like image 784
Victor Avatar asked Apr 11 '11 16:04

Victor


3 Answers

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

like image 134
Rachel Shallit Avatar answered Oct 13 '22 22:10

Rachel Shallit


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 
like image 30
Mike Lewis Avatar answered Oct 13 '22 20:10

Mike Lewis


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 %>
like image 20
fl00r Avatar answered Oct 13 '22 21:10

fl00r