I have releases that can have many artists and artists can appear on many releases. Artists can be created within my release form via nested attributes. What i'm having trouble with is getting find_or_create to work on an artist.
I have the following code defined in my models and as you can see a rather ridiculous get/set/delete routine in the ArtistRelease model to achieve the desired outcome. This does work, but I don't like it. I know there's a better way via find_or_create. Can anyone help? Where should I place the find_or_create for this to work?
class Release < ActiveRecord::Base
has_many :artist_releases, :dependent => :destroy
has_many :artists, :through => :artist_releases
accepts_nested_attributes_for :artists, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
accepts_nested_attributes_for :artist_releases
end
class Artist < ActiveRecord::Base
has_many :artist_releases
has_many :releases, :through => :artist_releases
end
class ArtistRelease < ActiveRecord::Base
belongs_to :artist
belongs_to :release
before_create :set_artist_id
after_create :destroy_artist
default_scope :order => 'artist_releases.position ASC'
private
def set_artist_id
a = Artist.where("name =?", artist.name).reorder("created_at").find(:first)
a.role = artist.role
a.position = artist.position
a.save
artist_id = a.id
self.artist_id = artist_id
end
def destroy_artist
c = Artist.count(:all, :conditions => [ "name = ?", artist.name])
if c > 1
a = Artist.where("name =?", artist.name).reorder("created_at").find(:last)
a.destroy
end
end
end