开发者

How to sort ActiveRecord results using an attribute in the superclass?

开发者 https://www.devze.com 2023-01-16 09:20 出处:网络
I have two models: class Manufacturer < ActiveRecord::Base has_many :models end class Model < ActiveRecord::Base

I have two models:

class Manufacturer < ActiveRecord::Base
  has_many :models
end

class Model < ActiveRecord::Base
  belongs_to :manufacturer
  belongs_to :model
end

What I want to be able to do is find all manufacturers whose models belong to a given category:

manufacturers = Model.find(:all, :conditions=>["vehicle_category_id = 1"], :include => :manufacturer, :group => "manufacturer_id").map {|model| model.manufacturer }

But I want to be able to order the results by manufacturer name i.e. manufacturer.name

Do you know how I can do this?

UPDATE:

This works for me, but seems very inefficient, must be a better way:

manufacturers = (Model.find(:all, :conditions=>["vehicle_category_id = 1"], :include => :manufacturer, :group => "manufacturer_id").map {|model| model.manufacturer }).compact.sort{|x,y| x.nam开发者_StackOverflow中文版e <=> y.name} 


Solution 1

Manufacturer.all(
  :condition => [ "EXISTS (
                    SELECT a.id 
                    FROM   models a 
                    WHERE  a.manufacturer_id     = manufacturers.id AND 
                           a.vehicle_category_id = ?
                   )",
                  1
                ],
  :order     => "manufacturers.name"
)

Solution 2

Manufacturer.all(
  :select    => "DISTINCT manufacturers.*",
  :joins     => :models,
  :condition => [ "models.vehicle_category_id = ?", 1],
  :order     => "manufacturers.name"
)
  • Solution 2 is uses rails constructs.

  • Solution 1 is faster than solution 2.

0

精彩评论

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

关注公众号