我已按照自動完成關聯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>
我也注意到:id_element =>「#artist_id」,什麼是應該的? –
我試圖將ID傳遞給連接表....但顯然這並不奏效! – Raoot