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?
You could do
But if you need only 10 users in the view, then you can limit it in the controller itself
Why don't you limit the users?
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)
If
@users
has more elements than you want to loop over, you can usefirst
orslice
:Using
first
Using
slice
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: