如何在Ruby on Rails中通过关联订购has_many?

问题描述 投票:57回答:8

鉴于以下AR模型,我希望在给定任务句柄时按姓氏按字母顺序对用户进行排序:

#user
has_many :assignments
has_many :tasks, :through => :assignments    

#assignment
belongs_to :task
belongs_to :user

#task
has_many :assignments
has_many :users, :through => :assignments

我想获得一个任务然后导航到其分配的用户,并按字母顺序对用户列表进行排序。

我一直在想我应该能够像这样将:order子句添加到has_many :users, :through => :assignments

#task.rb
has_many :assignments
has_many :users, :through => :assignments, :order => 'last_name, first_name'

但这不起作用。

在给定任务时,如何通过q​​azxswpoi对用户进行排序?

ruby-on-rails has-many-through
8个回答
68
投票

由于条件参数在Rails 4中已弃用,因此应使用范围块:

last_name

37
投票

Rails 3.x版本:

has_many :users, -> { order 'users.last_name, users.first_name' }, :through => :assignments

更新:这仅适用于Rails 3.x(也许在此之前)。对于4+,请参阅其他答案。


12
投票

has_many :users, :through => :assignments, :order => 'users.last_name, users.first_name' 方法运行良好,但涉及表名。有一种更好的方法:

M.G.Palmer's

7
投票

这对你有用吗?

has_many :users, :through => :assignments, :order => [ :last_name, :first_name ]

您可以在排序需要不同时定义其他命名范围。

# User.rb class User < ActiveRecord::Base default_scope :order => 'last_name ASC' ... end


6
投票

这对我有用(Rails 4.2)

不保留在直通地图上应用排序,也就是说这不足以使类型排序:

http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

所以我在每个实例中覆盖这个:

has_many    :disk_genre_maps,
            -> {order('disk_genre_map.sort_order')},
            :inverse_of => :disk,
            :dependent  => :destroy,
            :autosave   => true


has_many    :genres,    # not sorted like disk_genre_maps
            :through    => :disk_genre_maps,
            :source     => :genre,
            :autosave   => true

为分配工作,这应该是这样的(未经测试)

def genres  # redefine genres per instance so that the ordering is preserved
    self.disk_genre_maps.map{|dgm|dgm.genre}
end

4
投票

我正在使用Rails(5.0.0.1)并且可以在我的模型组中使用此语法进行排序,该组通过group_users有许多用户:

def genres= some_genres
    self.disk_genre_maps = some_genres.map.with_index do |genre, index|
        DiskGenreMap.new(disk:self, genre:genre, sort_order:index)
    end
end

根据您的需要调整代码。


2
投票

您还可以在分配表上创建一个新的“sort_order”列,并添加一个默认范围

# Associations.
has_many :group_users
has_many :users, -> { order(:name) }, through: :group_users

到你的作业模型。


0
投票

has_many:users, - > {order(:last_name,:first_name)} ,: through =>:assignments,source:'user'

© www.soinside.com 2019 - 2024. All rights reserved.