Question

Apologies if this has been asked before, I may have been searching for the wrong keywords.

I am trying to do an .each loop for all the rows of a database table named users for which name equals user1. How is that done?

My model User has a DB Table :users that contains these columns: name | title | details | amount

In my view I have this:

<div style="width:50%;float:left">
<h3>User1</h3>
<% @User1.each do |i| %>
  <p><%= i.title %></p>
  <p><%= i.details %></p>
  <p>$<%= i.amount %></p>
<% end %>
</div>

<div style="width:50%;float:left">
<h3>User2</h3>
  <% @User2.each do |i| %>
  <p><%= i.title %></p>
  <p><%= i.details %></p>
  <p>$<%= i.amount %></p>
<% end %>
</div>

For my controller I have this but it is giving an error:

@items = User.all
@User1 = @items.where(name: 'user1')
@User2 = @items.where(name: 'user2')

enter image description here

Was it helpful?

Solution

To iterate over an array of users matching those in a given list, use

in your controller:

 @users = User.where(name: list_of_names)

where list_of_names is an array of strings,

and, in your view:

 <% @users.each_with_index do |user, idx| %>
    <div id="user-<%= idx %>">
       <%= user.name %>
       <%= user.details %>
        # etc
    </div>
 <% end %>

and etc.

See the Rails guides for more.

OTHER TIPS

@user1 = User.where(name: "name1").first

@user2 = User.where(name: "name2").first

Is that what you want?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top