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.
精彩评论