views:

41

answers:

3
class Person
  belongs_to :team

class Status
  #has last_updated property

class Team
  has_many :members, :class => "Person"

Ok, so I have a Team class which has many People in it and each of those people has a status and each status has a last_updated property.

I'm currently rendering a partial with a collection similar to:

 =render :partial => "user", :collection => current_user.team.members

Now how do I go about sorting the collection by the last_updated property of the Status class?

Thanks in advance!

p.s. I've just written the ruby code from memory, it's just an example, it's not meant to compile but I hope you get the idea!

A: 

When you get the members of the team, you need to join status to pull it in. Create a named_scope (Rails 2.x) on Team that brings in members and :joins => :status, then :order_by => 'statuses.last_updated'. (also written from memory)

Jonathan Julian
+1  A: 

You have two possibilities:

1) Change the association definition to add the order clause.

class Team
  has_many :members, :class => "Person", :joins => :status, 
                   :order => "statuses.updated_at DESC"
end
current_user.team.members # ordered by updated_at

2) Pass the :order clause to the members method.

This method is appropriate if the order by column changes based on the context.

current_user.team.members( :joins => :status, 
                :order => "statuses.updated_at DESC")
KandadaBoggu
Assuming that `timestamp` is added to the Person table and the Status table is not used. Which is preferable unless more status information is stored.
Veger
+2  A: 

In addition to the options mentioned you may want to use a named_scope:

class Member
  named_scope :recently_active, :joins => :status, :order => "statuses.updated_at DESC"
end

# now you can do:
current_user.team.members.recently_active

If you always sort members like this consider using a default_scope

class Member
  default_scope :joins => :status, :order => "statuses.updated_at DESC"
end

# and you can use this client code
current_user.team.members