开发者

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
   e开发者_如何转开发nd   

 end


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")


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜