Topic: Sort Through Association

I have a table of Users and a table of Friendships. Each user has_many friendships, and each friendship belongs_to a user.

My problem is I have a friends list page which works great, but I want to sort it by a parameter of the user. I want to be able to say "sort my friends by name" essentially. Is there an easy way to do this?

Here is what I am trying:

@collection = Friendship.find(:all, :include => [:user],:order => "users.firstname ASC", :conditions => "friendships.status = 1 AND friendships.user_id = #{@user.id}" )

Thanks!

Last edited by SupaPuerco (2007-01-06 06:56:40)

Re: Sort Through Association

A given friendship needs to reference two users as it acts as a join model. How are you currently accomplishing this? Do you have user_id and friend_id columns in the friendships table? How is the association in the Friendship model set up?

Railscasts - Free Ruby on Rails Screencasts

Re: Sort Through Association

My friend model is set up like this:

class Friendship < ActiveRecord::Base
 
  belongs_to :user
  belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'
 
end

And my User model like this:
class User < ActiveRecord::Base
 
  has_many :friendships
  has_many :friends, :through => :friendships
end

Last edited by SupaPuerco (2007-01-06 17:15:24)

Re: Sort Through Association

Try including friend instead of user.

@collection = Friendship.find(:all, :include => :friend, :order => "users.firstname ASC", :conditions => "friendships.status = 1 AND friendships.user_id = #{@user.id}" )

Railscasts - Free Ruby on Rails Screencasts

Re: Sort Through Association

Thanks! That works great!