Sorting in Rails views without displaying duplicates
How do I sort in Rails view but without displaying any duplicate values?
I have the following ERB code.
<% @todos.each do |todo| %>
<h1><%= todo.due %></h1>
<br />
<%= todo.description %><b><%= todo.list %></b>
<br />
<% end %>
And will output the following:
2011-03-09 10:39:00 -0600
My Todo For Today My List
2011-03-09 10:39:00 GMT
My Another Todo for Toda开发者_StackOverflow社区y My List 2
2011-03-09 10:39:00 GMT
And Another Todo for Today My List
However, how do I make it output with the following format in Rails?
2011-03-09 10:39:00 GMT
My Todo For Today My List
And Another Todo for Today My List
My Another Todo for Today My List 2
@todos
is an Array and @todos.uniq! removes duplicates. There is a method sort! in the Array class which should do what you are looking for.
You should use group_by
method
<% @todos.group_by(&:due).each do |due, todos| %>
<h1><%= due %></h1>
<% todos.each do |todo| %>
<p><%= todo.description %> <b><%= todo.list %></b></p>
<% end %>
<% end %>
I would add a method to todo model, that returns list of items by a due date:
#models/todo.rb
def self.get_todo_by_due(due_date)
return Todo.where(:due => due_date)
end
And then change view:
<%distinct_due_dates = Todo.select("DISTINCT(due)") %>
<%distinct_due_dates.each do |item|%>
<% due_date = item.due %>
<h1><%= due_date %></h1>
<% get_todo_by_due(due_date).each do |todo|%>
<br />
<%= todo.description %><b><%= todo.list %></b>
<br />
<% end%>
<% end%>
精彩评论