js111
js111

Reputation: 1314

Sort by date attribute in rails list

I have a table in my app that currently displays items in the order in which they are created. I would like them to sort by my date attribute (<%= o.dateg %>) in chronological order. Whats the proper rails way to do this?

Controller:

def show
 @occasion = Occasion.find(params[:id])
end

View:

   <% @user.occasions.each do |o| %>
          <td><%= o.name %></td>
          <td><%= o.pname %></td>
          <td><%= o.dateg %></td>

Thanks!

Upvotes: 1

Views: 5366

Answers (2)

supermoogle
supermoogle

Reputation: 1207

In the view you can use sort e.g.

@user.occasions.sort {|a,b| b.dateg <=> a.dateg }.each do |o|

(this will be reverse chronological)

However you should really be doing this in the model not in the view, a named scope would work fine:

class User < ActiveRecord::Base
  has_many :occasions
  scope :recent_occasions, order('dateg desc')
end

Then use

@user.recent_occasions.each do |o|

Upvotes: 3

Wawa Loo
Wawa Loo

Reputation: 2276

You must have that, right?

class User < ActiveRecord::Base
  has_many :occassions
end

You can change the has_many to:

has_many :occasions, order: 'dateg desc'

Upvotes: 3

Related Questions