基本上我有一个 has_many 关联。我想创建另一个关联,仅过滤原始关联中的项目。
class Track
belongs_to :playlist
end
class Playlist
has_many :tracks
has_many :five_start_tracks, -> { what to write here? }
has_many :long_tracks, -> { ... }
end
有办法做到这一点还是我应该这样做
def five_star_tracks
tracks.where(rating: 5)
end
def long_tracks
tracks.where("duration_seconds > ?", 600)
end
是的,您可以将范围添加到
has_many
关联。但是您还必须将类名添加到关联中,因为 Ruby on Rails 无法再从名称中猜测它。
class Track
belongs_to :playlist
end
class Playlist
has_many :tracks
has_many :five_start_tracks, -> { where(rating: 5) }, class_name: 'Track'
has_many :long_tracks, -> { where('duration_seconds > ?', 600) }, class_name: 'Track'
end