我有 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
列排序?
最佳答案
您可以使用 default_scope
对于 阵容
模型:
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 .
关于ruby-on-rails - 如何在连接模型中按列对关联模型进行排序(:through),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991239/