views:

246

answers:

1

Hello, I was wondering if it was possible to use the find method to order the results based on a class's has_many relationship with another class. e.g.

# has the columns id, name
class Dog < ActiveRecord::Base
  has_many :dog_tags
end

# has the columns id, color, dog_id
class DogTags < ActiveRecord::Base
  belongs_to :dog
end

and I would like to do something like this:

@result = DogTag.find(:all, :order => dog.name)

thank you.

+1  A: 

You need to join the related table to the request.

@result = DogTag.find(:all, :joins => [:dog], :order => 'dog.name')
Damien MATHIEU
should be DogTag.find(:all, :joins => :dog, :order => 'dogs.name') =)
Staelen
Thank you for the solution. I'm sure you know, but for anyone else, I found that the order had to be the table name as well, i.e. I had to pluarlize it: 'dogs.name' not 'dog.name'
Evan