【问题标题】:Rails duplicate entries on has_many throughRails 通过 has_many 重复条目
【发布时间】: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


【解决方案1】:

您遇到的问题可能是自定义验证在插入记录之前在数据库上运行选择。

这意味着如果运行两个并发验证,它们都将看不到唯一记录,并继续执行可能正在插入记录的下一行代码,从而导致重复插入。

我建议使用Active Record Import,而不是进行检查,而是在Playlist 上设置唯一约束并执行更新插入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2011-11-19
    • 2011-02-04
    • 2010-11-21
    相关资源
    最近更新 更多