Sorting has_many - via parent association

Hey,

I’m trying to sort an array result through a has many relationship, but
am getting a little stuck. My bands model has_many videos. I am trying
to sort a list of videos by band.name and then video.name. I’ve seen
that :include can be used for child sorting, is there, something that
could work in reverse. Thanks!

My Models:

class Band < ActiveRecord::Base
has_many :videos
end

class Video < ActiveRecord::Base
belongs_to :band
end

-Mario

On 11/1/07, Mario F. [email protected] wrote:

class Band < ActiveRecord::Base
has_many :videos
end

class Video < ActiveRecord::Base
belongs_to :band
end

Video.find(:all, :include => :bands, :order => “bands.name,
videos.name”)

should work, I think.

Note that the include option also means that all of the bands will be
instantiated on this query, which may or may not be a good thing
depending on what you’re going to do next.

I wrote a patch which is now in edge rails which extends the :joins
option to take the same kind of values as includes. This lets you do:

Video.find(:all, :joins => :bands, :order => “bands.name, videos.name”)

Which does the same thing, but only instantiates the videos.

Be warned though, this patch may or may not make it into Rails 2.0
since it’s very new.

–
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Thanks for the help. I was a little reluctant to use edge rails. After
some further review, I discover that the include statement needed to
refer to the name of the association and not the name of the table. So
you can sort by parent using the following:

#Controller Action Code
Video.find(:all, :include => :band, :order => ‘bands.name ASC’ )

Built on these models Models:

class Band < ActiveRecord::Base
has_many :videos
end

class Video < ActiveRecord::Base
belongs_to :band
end