2

I'm still new to rails and I'm having trouble validating across models.

I have two models, Artists and Songs associated with a many to many relationship. I would like to have a validation in the song model that checks that song url_slug is unique for each artist. I have tried using :scope but I don't seem to be able to call the associated artist id.

I'm pretty lost here so any help would be appreciated.

Thanks,

Here is my song model:

class Song< ActiveRecord::Base
 has_and_belongs_to_many:artists

 #creates Url Slug
 #before_create :generate_slug

 before_update :generate_slug

 validates_uniqueness_of :song_url_slug, :scope => self.artist.id

   protected
 def generate_slug
     self.song_url_slug = song_name.gsub(/\W+/, ' ').strip.downcase.gsub(/\ +/, '-')
 end


#def url_slug_uniqueness
  #artist_song = self.song_name.find(:artist_id])
     #if self.exists?(:conditions => {:song_name => artist_song})
      # errors.add(:song_name, :name_taken, :song_name=> "#{artist_song}1")
    #end
# end
#end

1 Answers1

0

The first thing to do is try getting rid of the before_create :generate_slug and before_update :generate_slug lines and replace them with

  before_validation :generate_slug

Your uniqueness validation may work then.

Preacher
  • 2,410
  • 1
  • 19
  • 29