Loop in Ruby on Rails html.erb file

54,573

Solution 1

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)

Solution 2

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)

Solution 3

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)

Share:
54,573
Stark_kids
Author by

Stark_kids

Updated on February 20, 2020

Comments

  • Stark_kids
    Stark_kids about 4 years

    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?

  • Zack Xu
    Zack Xu over 8 years
    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).
  • user3505901
    user3505901 over 7 years
    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.