40

everybody I'm brand new with Ruby on Rails and I need to understand something. I have an instance variable (@users) and I need to loop over it inside an html.erb file a limitated number of times. I already used this:

<% @users.each do |users| %>
   <%= do something %>
<%end %>

But I need to limitate it to, let's say, 10 times. What can I do?

Stark_kids
  • 507
  • 1
  • 5
  • 17

3 Answers3

49

If @users has more elements than you want to loop over, you can use first or slice:

Using first

<% @users.first(10).each do |users| %>
  <%= do something %>
<% end %>

Using slice

<% @users.slice(0, 10).each do |users| %>
  <%= do something %>
<% end %>

However, if you don't actually need the rest of the users in the @users array, you should only load as many as you need by using limit:

@users = User.limit(10)
infused
  • 24,000
  • 13
  • 68
  • 78
9

You could do

<% for i in 0..9 do %>
  <%= @users[i].name %>
<% end %>

But if you need only 10 users in the view, then you can limit it in the controller itself

@users = User.limit(10)
Santhosh
  • 28,097
  • 9
  • 82
  • 87
  • Doing this limit in the controller is the right approach. Imagine you have 1 million user records and you only need to show 10 users! By asking database to limit the number of rows returned, it's better performance on the database and memory usage. If you want some flexibility in the view file, you can ask controller to return, say, 50 users, and let the view limit to 10 (a variable number under 50). – Zack Xu Nov 03 '15 at 09:45
  • 1
    It's considered bad practice in Ruby to use For loops, should use a .each loop if possible. As the answer by Mohamed El Mahallawy shows. – user3505901 Dec 22 '16 at 21:40
0

Why don't you limit the users?

<%= @users.limit(10).each do |user| %>
 ...
<%end%>

That'd still use ActiveRecord so you get the benefit of AR functions. You can also do a number of things too such as:

@users.first(10) or @users.last(10)

Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84