dannymcc
dannymcc

Reputation: 3814

Grouping records with headings in Rails 3

I have an articles model in my Rails 3 application. The article model has a column called categories which is set using a select box in the new form view. (It's a select box because the options should never change and there are only four of them).

The index view code I have is as follows:

<% @articles.category.each do |article| %>
 <%= article.category %>
 <% @articles.each do |article| %>
  <tr>
    <td><%= article.title %></td>
    <td><%= article.author %></td>
    <td><%= article.category %></td>    
    <td><%= link_to 'Show', article %></td>
    <td><%= link_to 'Destroy', article, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
 <% end %>
<% end %>

I have grouped by category in my controller:

@articles = Article.group(:category).order('title ASC')

However, this results in an exception which points to the following line <% @articles.category.each do |article| %>.

What is the tidiest (from within my view code) way of achieving the following:

So each article is listed under it's category.

Upvotes: 3

Views: 1223

Answers (1)

melekes
melekes

Reputation: 1888

I'd suggest you to use group_by method (Documentation):

# in your controller
articles = Article.order('title ASC')
@grouped_articles = articles.group_by &:category


# in your view
<% @grouped_articles.each do |category, articles| %>
  <%= category %>
  <% articles.each do |a| %>
    <tr>
      <td><%= a.title %></td>
      <td><%= a.author %></td>   
      <td><%= link_to 'Show', a %></td>
      <td><%= link_to 'Destroy', a, confirm: 'Are you sure?', method: :delete %>       </td>
    </tr>
  <% end %>
<% end %>

Upvotes: 8

Related Questions