Rails:使用has_many / belongs_to关系进行排序

我想知道是否可以使用find方法根据类与另一个类的has_many关系对结果进行排序。 例如

# has the columns id, name class Dog < ActiveRecord::Base has_many :dog_tags end # has the columns id, color, dog_id class DogTags < ActiveRecord::Base belongs_to :dog end 

我想做这样的事情:

 @result = DogTag.find(:all, :order => dog.name) 

谢谢。

您需要将相关表加入请求。

 @result = DogTag.find(:all, :joins => :dog, :order => 'dogs.name') 

请注意, dogs:order语句中是复数。

在Rails 4中,应该这样做:

 @result = DogTag.joins(:dog).order('dogs.name') 

或者范围:

 class DogTags < ActiveRecord::Base belongs_to :dog scope :ordered_by_dog_name, -> { joins(:dog).order('dogs.name') } end @result = DogTags.ordered_by_dog_name 

第二个更容易在测试中模拟,因为控制器不必知道模型细节。