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
第二个更容易在测试中模拟,因为控制器不必知道模型细节。
- Active Record不存在连接表记录的情况
- 有什么区别:before_save和:before_update Active Record回调?
- 我的模型有一个模型列表。 如何从数据库加载它但限制列表中的项目数?
- 何时保存has_many关系中的Active Record对象?
- Rails has_many通过使用source和source_type别名来处理多种类型
- 基于params的动态ActiveRecord查找器方法链接
- Rails 5.1:销毁“has_many:through”与限制关联的记录
- 通过未保存的子关联访问父级(has_many)
- 连接池问题与rufus-scheduler中的ActiveRecord对象有关