我有許多藝術家和藝術家可以出現在許多版本的發佈。藝術家可以通過嵌套屬性在我的發佈表單中創建。我遇到麻煩的是讓find_or_create工作在藝術家身上。Rails 3.1 - 對於HABTM關係的nested_attribute的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