How can I show together in the views multiple attributes from different entries, that have the same name, like “nested” attributes?

Schmitt

New Member
#1
In a rental system, I have a model called Boardgame, with the attributes: name, copy and situation. Situation is another model, with belongs_to.

So an example of my database:
Mã:
Catan, copy 1, available
War, copy 1, rented
War, copy 2, available
War, copy 3, rented
My code in the index view is (without the HTML):
Mã:
<% @boardgames.each do |boardgame| %>
  <%= boardgame.name %>
  <%= boardgame.copy %>
  <%= boardgame.situation.name %>
 <% end %>
And it shows:
Mã:
Catan
    - copy 1: available
War
    - copy 1: rented
War
    - copy 2: available
 War
    - copy 3: rented
But I want to show in this way:
Mã:
Catan:
- copy1: available

War:
 - copy 1: rented
 - copy 2: available
 - copy 3: rented
Now I see that the better was to make the "copy" attribute another model, nested. But the application is already in production, with all the rents records, clients and payments, etc.

How can I say to Ruby on Rails to check if the name is the same and in that case show the attributes in a nested form?
 

Admin

Administrator
Thành viên BQT
#2
You could use Enumerable#group_by on@boardgames to get them arranged the way you want (preferably not in the view itself).
Mã:
<% @boardgames.group_by(&:name).each do |name, games| %>
  <h3><%= name %></h3>
  <ul>
    <% games.each do |game| %>
      <li>copy <%= game.copy %>: <%= game.rented %>
    <% end %>
  </ul>
<% end %>