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:
- Category 1
- Article 1
- Article 2
- Category 2
- Article 5
- Category 3
- Article 8
So each article is listed under it’s category.
I’d suggest you to use group_by method (Documentation):