我已经按照自动完成协会 Railscast 将“艺术家”添加到我的“发布”中。一切似乎都运行良好,但我随后注意到它每次都在创建一个新艺术家,而不是通过自动完成选择现有的艺术家。
与 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>