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?
What is erb? 'erb' Refers to Embedded Ruby, which is a template engine in which Ruby language embeds into HTML. To make it clearer: Is the engine needed to be able to use the Ruby language with all its features inside HTML code. We’ll see its application in the next sections. Rails use erb as its default engine to render views.
ERB provides an easy to use but powerful templating system for Ruby. Using ERB, actual Ruby code can be added to any plain text document for the purposes of generating document information details and/or flow control. require 'erb' x = 42 template = ERB. new <<-EOF The value of x is: <%= x %> EOF puts template. result ( binding )
Ruby - Loops. Loops in Ruby are used to execute the same block of code a specified number of times. This chapter details all the loop statements supported by Ruby.
HTML.ERB is HTML mixed with Ruby, using HTML tags. All of Ruby is available for programming along with HTML. Following is the syntax of using Ruby with HTML − <%%> # executes the Ruby code <%=%> # executes the Ruby code and displays the result
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With