Ordering by associated columns (pleeease help)

Sumeet Panchal wrote:


I am stuck pretty bad please help. any comment is helpful. I have say three models Customer(fields are id, name, cell_phone, primary_address_id)    belongs_to :primary_address, :class_name => 'CustomerAddress', :foreign_key => 'primary_address_id'    has_many :customer_addresses end

CustomerAddress(fields city, customer_id, state)    belongs_to :customer end

so basically I have many addresses for a customer, and one of which is primary address. so I have this relations ship customer.primary_address.

Now I want to write a query by using find or paginate. like: Customer.find [arra of id], :order => "primary_address.city ASC" The problem is that it is not ordering by associated columns. It says no column primary_address.city found. I am trying to use include but it do not works, :join how can I use it. Please help is there any way to order by associated columns.

Thanks Sumeet Panchal

You can use join as Customer.find(:all, :joins => "customers inner join customer_address as b on customers.primary_address_id=b.id") and in this you can use ordering.


join will work, even :include will work. but this reduce performance for query.