简体   繁体   English

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

[英]Rails: order using a has_many/belongs_to relationship

I was wondering if it was possible to use the find method to order the results based on a class's has_many relationship with another class. 我想知道是否可以使用find方法根据类与另一个类的has_many关系对结果进行排序。 eg 例如

# 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

and I would like to do something like this: 我想做这样的事情:

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

thank you. 谢谢。

In Rails 4 it should be done this way: 在Rails 4中,应该这样做:

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

or with scope: 或者范围:

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

@result = DogTags.ordered_by_dog_name

The second is easier to mock in tests as controller doesn't have to know about model details. 第二个更容易在测试中模拟,因为控制器不必知道模型细节。

You need to join the related table to the request. 您需要将相关表连接到请求。

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

Note that dogs is plural in the :order statement. 请注意, dogs:order语句中是复数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM