FattRyan
FattRyan

Reputation: 896

Rails - How to sort data

I have a simple app that has a list of clients in one table (just a name attribute), and in another table, keeps track of their quarterly savings (amount, quarter, and year attributes). A Client has_many :savings and Saving belongs_to :client. As savings data gets entered, there is a spot to enter the quarter and the year (two separate fields), both integers. On the clients show page, I list the quarters that have savings data entered by doing the following:

In my clients_controller under show:

@savings = @client.savings  

In my clients show.html.erb:

<% @savings.each do |saving| %>  
  <%= link_to "Q#{saving.quarter} #{saving.year}", edit_saving_path %>  
<% end %>  

On the screen, this renders the quarter and date of the entries like "Q1 2011" and so on. However, it puts them in order of when they were entered, and I want them be in chronological order.

Two questions, how do I do order the entries, and second, is this the right way to list those savings entries for each client?

Upvotes: 1

Views: 1083

Answers (1)

Maxem
Maxem

Reputation: 2684

1:

@savings = @client.savings.order("year")

2: You should probably override to_s with this representation or at least put it in a helper as you'll probably need this representation "Q1 2011" more than once.

Bonus: it should be edit_saving_path(saving)

Upvotes: 2

Related Questions