2012-05-30 93 views
1

我已按照自動完成關聯Railscast將'Artists'添加到我的'Releases'中。一切看起來都很好,但我注意到它每次都會創建一個新的藝術家,而不是使用現有的藝術家,如果通過自動完成選擇的話。與嵌套屬性和多對多關係的自動完成關聯

與railscast不同,我使用的是多對多的關係,藝術家也被視爲發佈版本中的嵌套屬性,所以我意識到這個問題可能與其中一個或兩個有關。

下面是我的模型和相關的意見。在我看來,行self.artist = Artist.find_or_create_by_name(name) if name.present?沒有被使用。我以爲這是因爲我有f.autocomplete_field :name而不是f.autocomplete_field :artist_name但是當我改變爲我得到一個沒有方法的錯誤!

任何人都可以幫忙嗎?

class Release < ActiveRecord::Base 
    has_many :artist_releases 
    has_many :artists, :through => :artist_releases 

    accepts_nested_attributes_for :artists, :reject_if => lambda { |a| a[:name].blank? } 
    accepts_nested_attributes_for :artist_releases 

    def artist_name 
    artist.try(:name) 
    end 

    def artist_name=(name) 
    self.artist = Artist.find_or_create_by_name(name) if name.present? 
    end  
end 

class ArtistRelease < ActiveRecord::Base 
    belongs_to :artist 
    belongs_to :release 
end 

class Artist < ActiveRecord::Base 
    has_many :artist_releases 
    has_many :releases, :through => :artist_releases 
end 


#Release Form 
<%= form_for(@release) do |f| %> 
<%= f.text_field :title, :class => "text" %> 
    <%= f.fields_for :artists do |builder| %> 
    <%= render 'artist_fields', :f => builder %> 
    <% end %> 
    <p><%= link_to_add_fields "Add Artist", f, :artists %> </p> 
<% end %> 

#Artist Fields 
<p> 
<%= f.label :artist_name, "Artist" %><br /> 
<%= f.autocomplete_field :name, autocomplete_artist_name_releases_path, :id_element => '#artist_id', :class => "text" %> 
</p> 
+0

我也注意到:id_element =>「#artist_id」,什麼是應該的? –

+0

我試圖將ID傳遞給連接表....但顯然這並不奏效! – Raoot

回答

0

您應該把

<%= f.autocomplete_field :artist_name, autocomplete_artist_name_releases_path, :class => "text" %> 

其中f是形式發佈。但這分配給發佈#藝術家(只有一個),這應該是未定義的,因爲你的發佈模型has_many :artists

你可以做的是允許許多名稱在逗號分隔列表中。請注意,我們直接將其放在發佈表單中,不需要嵌套屬性。

#Release Form 
<%= form_for(@release) do |f| %> 
<%= f.text_field :title, :class => "text" %> 
... 
<%= f.autocomplete_field :artist_names, autocomplete_artist_name_releases_path, :class => "text", 'data-delimiter' => ',' %> 
<% end %> 
在釋放模型

,沒有嵌套的屬性需要。 。

class Release < ActiveRecord::Base 
    has_many :artist_releases 
    has_many :artists, :through => :artist_releases 

    attr_accessor :artist_names 
    def artist_names=(names) 
    self.artists = names.split(',').map { |name| Artist.find_or_create_by_name(name.strip) } 
    end 
end 

你可以嵌套屬性解決,但前提是你必須爲藝術家多個字段填寫推薦

+0

非常感謝,我會放棄並回報。 – Raoot

+0

當我嘗試你的建議以允許許多名字時,我得到'未定義的方法'artist_names''。任何想法爲什麼? – Raoot

+0

對不起,您還需要定義getter,也請參閱我的更新 –