简体   繁体   English

如何在Rails 4中控制联接记录的顺序

[英]How to control the order of joined records in Rails 4

Rails 4. Sqlite3 DB (for development). Rails 4. Sqlite3 DB(用于开发)。

My model looks like this: 我的模型如下所示:

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :people, through: :memberships
  has_many :notes, as: :notable

  scope :with_active_members, -> { joins(people: [:role]).where(people: {active: true}).uniq }

end

And I use it like this: 我这样使用它:

@groups = Group.with_active_members.order("groups.position")

The join works perfectly well. 连接效果很好。 But I want to order the people records alphabetically. 但是我想按字母顺序排序人们的记录。 To be very clear, I don't want to order the groups by their associated people. 非常清楚,我不想通过自己的关联人订购组。 I want the groups to be ordered by their position field but I want the associated collections of people to be ordered alphabetically. 我希望按position字段对这些组进行排序,但是我希望按字母顺序对相关的人员集合进行排序。 Can this be done with the ORM? 可以用ORM完成吗?

It appears that you can do this in the model: 看来您可以在模型中执行此操作:

has_many :people, ->{ order('first_name') }, through: :memberships

This works in some situations, but I'm not accepting it as the answer because what I really need is a way to set this in the controller, so that the order can be controlled dynamically. 这在某些情况下可行,但我不接受它作为答案,因为我真正需要的是一种在控制器中进行设置的方法,以便可以动态控制顺序。

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

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