Sorting by an attribute on a associated table

So, I have a User has_many :profiles. The most recently dated profile is
considered the current one. I need to sort these users by name, but the
name attribute is a member of the associated table.

Is there any easy way to do this other than with some ugly find_by_sql?

Maybe a more general question - is there a common solution to sorting in
Ruby?

Something like

@user.profiles.find(:all, :order => “name DESC”)

Bryan D. wrote:

So, I have a User has_many :profiles. The most recently dated profile is
considered the current one. I need to sort these users by name, but the
name attribute is a member of the associated table.

Is there any easy way to do this other than with some ugly find_by_sql?

Maybe a more general question - is there a common solution to sorting in
Ruby?

What about using acts_as_list, :order => :date_added (or whatever you
call that column)? Then you could say

def profile
profilies.first
end

… I think :slight_smile:

Perhaps I was unclear. I have no trouble sorting the profiles
themselves.

What I want to do is sort the USERS by an attribute on their most recent
profile. Something along the lines of:

@users = User.find(:all, :order => |user| {user.profile.firstname})

Of course I totally made that syntax up.

Bryan D. wrote:

I don’t know how to do this in SQL but I can give you some ruby that
will get you going.

@users = User.find(:all)
@users.sort_by {|user| user.profile.firstname}

This will be really slow compared to a pure SQL sort so I would still
look for a way to do that.

Matthew M.
blog.mattmargolis.net

Matthew M. wrote:

I don’t know how to do this in SQL but I can give you some ruby that
will get you going.

@users = User.find(:all)
@users.sort_by {|user| user.profile.firstname}

This will be really slow compared to a pure SQL sort so I would still
look for a way to do that.

Something like this should do the trick in pure SQL.

@users = User.find(:all, :include => :profile, :order =>
“profiles.firstname ASC”)

Or just do a join if you don’t want to instantiate all the profiles.

hth

Matthew M. wrote:

Bryan D. wrote:

I don’t know how to do this in SQL but I can give you some ruby that
will get you going.

@users = User.find(:all)
@users.sort_by {|user| user.profile.firstname}

This will be really slow compared to a pure SQL sort so I would still
look for a way to do that.

Matthew M.
blog.mattmargolis.net

Awesome, that’s exactly what I was looking for. Thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs