我有可以有很多艺术家的版本,并且艺术家可以出现在许多版本中。艺术家可以通过嵌套属性在我的发布表单中创建。我遇到的问题是让 find_or_create 为艺术家工作。
我在我的模型中定义了以下代码,您可以在 ArtistRelease 模型中看到一个相当荒谬的 get/set/delete 例程来实现预期的结果。这确实有效,但我不喜欢它。我知道通过 find_or_create 有更好的方法。任何人都可以帮忙吗?我应该把 find_or_create 放在哪里才能工作?
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