【发布时间】:2020-10-07 15:31:43
【问题描述】:
我有一个网站,可以跟踪收音机中播放的歌曲。自从将我的歌曲从 belongs_to :artist 更改为 has_many :artists 后,我在播放列表模型中看到重复的条目,其中一首歌有多个艺术家。重复条目的数量等于艺术家的数量。
设置如下:
# models/playlist.rb
class Playlist < ActiveRecord::Base
belongs_to :song
has_many :artists, through: :song
belongs_to :radiostation
validate :today_unique_playlist_item
end
# models/song.rb
class Song < ActiveRecord::Base
has_many :playlists
has_many :radiostations, through: :generalplaylists
has_many :artists_songs
has_many :artists, through: :artists_songs
end
# models/artist.rb
class Artist < ActiveRecord::Base
has_many :artists_songs
has_many :songs, through: :artists_songs
has_many :playlists, through: :songs
has_many :radiostations, through: :playlists
end
# models/artist_songs.rb
class ArtistsSong < ApplicationRecord
belongs_to :artist
belongs_to :song
end
我在播放列表上添加了一个自定义验证来检查唯一性。 RSpec 测试运行完美,但仍然存在重复条目。所以我的猜测是这必须是一个数据库问题。我正在使用 PostgreSQL。
# custom validation
def today_unique_playlist_item
exisiting_record = Generalplaylist.joins(:song, :radiostation).where('songs.id = ? AND time = ? AND radiostations.id = ? AND generalplaylists.created_at > ?', song_id, time, radiostation_id, 1.day.ago).present?
errors.add(:base, 'none unique playlist') if exisiting_record
end
旁注:我只获取自当前广播时间(属性
playlist.time)没有日期以来的最后一天。当前格式:22:00
我正在考虑在架构中的播放列表模型上建立一个索引,但不确定这是否能解决问题以及放在那里的内容。
欢迎任何帮助。
【问题讨论】:
-
一个播放列表不应该有很多歌曲吗?
标签: ruby-on-rails postgresql duplicates