1

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 Today 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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 %>

Comments

1

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%>

1 Comment

You could also use Todo.find_by_due

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.