itx
itx

Reputation: 1399

Displaying data in horizontal format

Is there way to generate data to horizontal table in rails ? please guide me

<thead>
  <tr>
    <% @products.each do |pr| %>
      <th width="25px"><%= pr.name %></th>
    <% end %>
  </tr>
  <tr>
    <% @products.each do |pr| %>
      <th width="25px"><%= pr.brand %></th>
    <% end %>
  </tr>
</thead>

table products on database

|  name  | brand  |
-------------------
|   A    | brand1 |
|   B    | brand2 |
|   C    | brand3 |

I want to generate on view looks like :

|  A     |   B    |   C    |
----------------------------
| brand1 | brand2 | brand3 |

Upvotes: 2

Views: 865

Answers (3)

Pramod Shinde
Pramod Shinde

Reputation: 1892

Use collect to build Hash

<tr>   
  <% @products.collect{ |p| {name: p.name, brand: p.brand }}.each do |pr| %>
    <th width="25px"><%= pr[:name] %></th>
    <th width="25px"><%= pr[:brand] %></th>
  <% end %>
</tr>

Upvotes: 1

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

The best is to use transpose:

<% @products.collect{|p| [p.name, p.brand]}.transpose.each do |line| %>
  <tr>
    <% line.each do |cell| %>
      <td><%= cell %></td>
    <% end %>
  </tr>
<% end %>

Explanations:

@products.collect{|p| [p.name, p.brand]} will generate the following array: [ ['A', 'brand1'], ['B', 'brand2'], ['C', 'brand3'] ]

transpose will transpose your array like this: [ ['A', 'B', 'C'], ['brand1', 'brand2', 'brand3'] ]

When looping on that array, the first line will be your product names, the second line will be your brands names.

Careful not to use on very large result set, because @products.collect is eager loading

Upvotes: 2

Pavan
Pavan

Reputation: 33542

Try with each_slice

<tr>
    <% Product(1..10).each_slice(3) do |pr| %>
      <th width="25px"><%= pr.name %></th>
      <th width="25px"><%= pr.brand %></th>
    <% end %>
  </tr>

Note: Didn't tested it.Just have a try and let me know.

Upvotes: 0

Related Questions