Forum: Ruby on Rails multiple items on 1 column

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel W. (Guest)
on 2006-01-10 09:23
(Received via mailing list)
Hello,

I am trying to put multiple items in one column and can't seem to get
the syntax right.

These are images and the image url's are being pulled from a database.
It seems that <tr></tr> is the trigger to go onto the next item.

Here is the code from the controller:

def list
   @items = Item.find_all
end

Here is the code from list.rhtml file:

<% @items.each do |item| %>
  <tr>
    <td>
       <%= image_tag item.image_url, %>
    </td>
  </tr>
<% end %>

I have also tried:

<% for item in @items %>
  <tr>
    <td>
       <%= image_tag item.image_url, %>
    </td>
  </tr>
<% end %>


If I put multiple columns in the same row,

<% for item in @items %>
  <tr>
    <td>
       <%= image_tag item.image_url, %>
    </td>
    <td>
        <%= image_tag item.image_url, %>
     </td>
     <td>
        <%= image_tag item.image_url, %>
     </td>
  </tr>
<% end %>


 it puts the same image 3 times and then the next row is the next item 3
times until the next row. How do I get 3 different images on the same
row?

Any code examples would be greatly appreciated.

TIA

Dan
Jens-Christian F. (Guest)
on 2006-01-10 10:29
(Received via mailing list)
>
> These are images and the image url's are being pulled from a
> database.  It seems that <tr></tr> is the trigger to go onto the
> next item.

<tr> is the "table row" tag of html, that creates a new row in your
table.

try the following in your view:

<% counter = 0 -%>
<% @items.each do |item| -%>
<%= "<tr>" if counter % 3 == 0 -%>
<td>
     <%= image_tag item.image_url -%>
</td>
<%= "</tr>" if counter % 3 == 0 -%>
<% counter += 1 -%>

<% end -%>

that will increment a counter and put in the table rows every time,
the counter reaches a number that is divisible by 3 ( % is the modulo
function )

hth jc
Alex Y. (Guest)
on 2006-01-10 10:50
(Received via mailing list)
Jens-Christian F. wrote:
> <% counter = 0 -%>
> <% @items.each do |item| -%>
> <%= "<tr>" if counter % 3 == 0 -%>
> <td>
>     <%= image_tag item.image_url -%>
> </td>
> <%= "</tr>" if counter % 3 == 0 -%>
> <% counter += 1 -%>
>
> <% end -%>
>
Untested, but clearer (I think :-) ):

<% while @items.length>0 -%>
   <tr>
     <% 3.times do -%>
       <% if (item = @items.shift) -%>
         <td><%= image_tag item.image_url %></td>
       <% end -%>
     <% end -%>
   </tr>
<% end -%>

--
Alex
Daniel W. (Guest)
on 2006-01-10 11:18
(Received via mailing list)
Jens-Christian and Alex,

Thank you both for the input.

<% The 3.times do %>  is exactly what I was looking for.

Dan
This topic is locked and can not be replied to.