Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop in Ruby on Rails html.erb file

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?

like image 806
Stark_kids Avatar asked Jul 03 '14 16:07

Stark_kids


People also ask

What is Erb in rails?

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.

How do I use Erb in Ruby?

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 )

What is a loop in Ruby?

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.

How to use Ruby with HTML?

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


2 Answers

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) 
like image 93
infused Avatar answered Sep 28 '22 08:09

infused


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) 
like image 42
Santhosh Avatar answered Sep 28 '22 10:09

Santhosh