title: Rails duplicate entries on has_many through
body: <p>I have a website that keeps track of which songs are played on the radio. Since changed my song from <code>belongs_to :artist</code> to <code>has_many :artists</code> I'm seeing duplicate entries in the playlist model where a song has multiple artists. The number of duplicate entries is equal to the number of artists.</p>
  
  <p>Here's the setup:</p>
  
  <pre><code># models/playlist.rb
  class Playlist &lt; ActiveRecord::Base
    belongs_to :song
    has_many :artists, through: :song
    belongs_to :radiostation
    validate :today_unique_playlist_item
  end
  
  # models/song.rb
  class Song &lt; 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 &lt; 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 &lt; ApplicationRecord
    belongs_to :artist
    belongs_to :song
  end
  </code></pre>
  
  <p>I've added a custom validation on the playlist to check for the uniqueness. The RSpec tests run perfectly but still there a duplicate entries. So my guess is that is has to be a database issue. I'm using PostgreSQL.</p>
  
  <pre><code># 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 &gt; ?', song_id, time, radiostation_id, 1.day.ago).present?
    errors.add(:base, 'none unique playlist') if exisiting_record
  end
  </code></pre>
  
  <blockquote>
    <p>Side note: I'm only fetching the last day since the current broadcast time (attribute <code>playlist.time</code>) doesn't have the date. Current format: <code>22:00</code></p>
  </blockquote>
  
  <p>I'm thinking to but an index on the playlist model in the schema but not sure if that will fix the issue and what to put there.</p>
  
  <p>Any help is welcome.</p>