TangoKilo
TangoKilo

Reputation: 1785

Displaying data from a collect in rails

I currently have models that can be described as follows:

Songs can have many setlists through Allocations Allocations belong to songs and setlists Setlists can have many songs in them through allocations

Songs have a title, artist, and a musical key.

Basically I'm setting up the new setlist view where a musician can select any existing songs from the library to add to a setlist. I want to do something along these lines:

     <thead>
        <th>Title</th>
        <th>Artist</th>
        <th>Root Key</th>
    </thead>
    <tbody>
      INSERT CODE HERE TO DISPLAY DATA
    </tbody>

At the moment I'm using the following code to get the data but I don't know if there's a way to separate it out into the relevant cells in the table:

<% songs = Song.all.collect {|s| [ s.title, s.artist, s.key ] }  %>
<% songs.sort! %>

I'm not sure if this is this is the best way to go about doing this so if anyone could suggest an alternative that would be fantastic too. Thanks in advance!

Upvotes: 0

Views: 82

Answers (2)

kalys.osmonov
kalys.osmonov

Reputation: 522

Fetching data is controller's responsibility.

def index
  @songs = Song.select([:title, :artist, :key]).all
end

And view:

  <tbody>
      <% @songs.each do |song| %>
        <tr>
          <td><%= song.title %></td>
          <td><%= song.artist %></td>
          <td><%= song.key %></td>
        </tr>
      <% end %>
  </tbody>

Upvotes: 4

TangoKilo
TangoKilo

Reputation: 1785

I managed to solve the problem as follows:

<tbody>
          <% songs.each do |n| %>
            <tr>
              <td><%= n[0], '#' %></td>
              <td><%= n[1], '#' %></td>
              <td><%= n[2], '#' %></td>
            </tr>
          <% end %>
      </tbody>

I'm still not sure whether or not this is best practice or not so if anyone know of a better way please let me know. Thanks :)

Upvotes: 0

Related Questions