views:

63

answers:

2

Sorry if the title is not enough to understand what i am asking about. I am rails developer and i used multiple lines of <% %> in my views but now i realized that it's not best practice so i came here and like to you all excellent guys what is the correct way in ROR?

For example if i required to something like following

 <% user =User.all %>
 <% name= [] %>
 <% count = 0 %>
  <% for user in users %>
    <% name << user.name %>
    <% count+=1%>
  <% end %>

Can i do it as follows ?

 <% user =User.all 
    name= [] 
    count = 0
    for user in users 
      name << user.name 
      count+=1
    end 
 %>

I know better way of collecting element from array But above is just example. But my question is, is it possible and if yes which is the correct way?

+1  A: 

I think the correct way is something totally different: move logic out of views.

This blog post explains what I mean.

Ermin
I totally agree. The logic should be in the controller, or if it's something to do with rendering the view, it could be in a helper. If you do it like that, there's hardly ever a need for multiple lines of code in the view.
Alex - Aotea Studios
it just example dear i know it's not logic written for a view but i just want to know what should used when you have to write something like above.
Salil
A: 

Using just a single pair of tags per code block is certainly preferable if only because it makes the output smaller.

The code should really rather look like

<% names = User.all.map(&:name) %>

Note that "count" can be obtained via names.size.

If you need to mix <% and <%= you need to switch:

<% for user in User.all %>
<%= user.name %></br>
<% end %>
Robert Klemme