Mellon
Mellon

Reputation: 38902

ActiveRecord query ordering

Suppose I have the following models:

class Car < ActiveRecord::Base
  belongs_to :seat
  ...
end

class Seat < ActiveRecord::Base
  belongs_to :color
  ...
end 

class Color < ActiveRecord::Base
  attr_reader :name
  ...
end

If I have get a list of Cars, and I want to order the Cars by color.name, how to write the order query?

class Car < ActiveRecord::Base
   belongs_to :seat
   ...
   def cars_order_by_color(car_ids)
       where(:id=>car_ids).order(?????) #HOW TO ORDER BY COLOR.name
   end   

 end

Upvotes: 1

Views: 702

Answers (2)

Dylan Markow
Dylan Markow

Reputation: 124469

If you use a joins on your query, you can then sort by the joined tables (either seats or colors):

Car.joins(:seat => :color).order("colors.name")

Upvotes: 1

Harry Joy
Harry Joy

Reputation: 59694

To retrieve records from the database in a specific order, you can specify the :order option to the find call.

 Car.order("color")

You could specify ASC or DESC as well:

 Car.order("color DESC")

For more help in query look here: active_record_querying

Hope this helps.

Edit

You can use find_by_sql:

Car.find_by_sql("SELECT * FROM clients
  INNER JOIN orders ON clients.id = orders.client_id
  ORDER clients.created_at desc")

Write appropriate query.

Upvotes: 0

Related Questions