Topic: How do you order through associations?

I can't seem to find an answer for this question and have tried a few variations.

I have a Category and Subcategory model. When I'm listing the subcategories, I want to be able them via their associated category ascending. I have my models setup correctly (i.e. belongs_to and has_many)

# Attempt 1
@subcategories = Subcategory.find(:all, :order => 'category.category asc')


# Attempt 2
@subcategories = Subcategory.find(:all, :order => 'categories.category asc')


p.s. Subcategory model has a category_id field. Category model has a category field which is the name of the category.

It would save me an awful headache if someone could shed some light on this. Thanks

Re: How do you order through associations?

fonziguy wrote:

I can't seem to find an answer for this question and have tried a few variations.

I have a Category and Subcategory model. When I'm listing the subcategories, I want to be able them via their associated category ascending. I have my models setup correctly (i.e. belongs_to and has_many)

# Attempt 1
@subcategories = Subcategory.find(:all, :order => 'category.category asc')


# Attempt 2
@subcategories = Subcategory.find(:all, :order => 'categories.category asc')


p.s. Subcategory model has a category_id field. Category model has a category field which is the name of the category.

It would save me an awful headache if someone could shed some light on this. Thanks

The order option takes a simple fragment of sql - literally what you would put after "order by" in a regular sql query.  So, what you're saying above is

select * from subcategories order by category.category asc;

Which makes no sense - there's no table called 'category' and subcategories doesn't have a field called 'category'.

If you want to do a join on another table to order by its fields you can use the :include option.

@subcategories = Subcategory.find(:all, :include => [:categories], :order => 'categories.category')

This should work, i think.  I have to say though, that giving the categories table a field called 'category' is asking for trouble.  It's going to cause confusion when you say things like "@subcategory.category.category" for example.  Wouldn't it be better to call that field 'name', if it represents the name?

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: How do you order through associations?

Hi Max,

Thanks for your solution!
And advice duly noted.