如何按连接模型中的列对相关模型进行排序(:through)

时间:2016-01-25 11:15:05

标签: ruby-on-rails ruby ruby-on-rails-4

我有3个型号:

活动,阵容,艺术家

class Event
  has_many :lineups
  has_many :artists, -> { uniq }, through: :lineups
end

class Artist
  has_many :events, through: :lineups
  has_many :lineups
end

class Lineup
  belongs_to :event
  belongs_to :artist
end

阵容有artist_order整数列。

默认情况下,我可以通过排序Event.last.artists列对artist_order进行排序?

3 个答案:

答案 0 :(得分:3)

您可以将default_scope用于Lineup型号:

class Lineup
  default_scope { order(:artist_order) } # or order('artist_order DESC')
end

这样,无论何时调用阵容集合,都会按artist_order列进行排序。

其他方式是直接在has_many关系中指定订单:

has_many :lineups, -> { order(:artist_order) }

后者可能是更好的选择,因为default_scope有时是considered to be a bad idea

答案 1 :(得分:1)

我认为您只需将-> { order "artist_order ASC" }添加到lineups模型中的Artist关联

Artist: 
  has_many :events, through: :lineups
  has_many :lineups, -> { order "artist_order ASC" }

现在Event.last.artists应该为您提供按阵容artist_order

排序的结果

PS: 未经测试。

答案 2 :(得分:1)

您可以在任何关联中添加订单,只需在order关联前添加lineups

has_many :lineups,-> { order(:artist_order) }

检查此http://apidock.com/rails/v4.2.1/ActiveRecord/Associations/ClassMethods/has_many以获取完整参考。

相关问题