我在发布表单上使用rails3-jquery-autocomplete gem我的艺术家字段,并希望确保任何新版本使用现有艺术家的ID(如果通过自动完成找到)或创建新艺术家(如果找不到) 。目前,自动完成宝石按预期返回艺术家,但即使该艺术家存在,也会创建一个新条目。
我的模型如下:
class Artist < ActiveRecord::Base
has_and_belongs_to_many :releases
end
class Release < ActiveRecord::Base
has_and_belongs_to_many :artists
accepts_nested_attributes_for :artists, :reject_if => lambda { |a| a[:name].blank? }
end
和控制器:
class ArtistsController < ApplicationController
def index
@artists = Artist.find(:all, :order => :name, :group => :name)
end
def create
@release = Release.find(params[:release_id])
@artist = @release.artists.create(params[:artist])
redirect_to release_path(@release)
end
def destroy
@release = Release.find(params[:release_id])
@artist = @release.artists.find(params[:id])
@artist.destroy
redirect_to release_path(@release)
end
end
class ReleasesController < ApplicationController
autocomplete :artist, :name
def new
@release = Release.new
@release.artists.build
end
def create
@release = Release.new(params[:release])
@release.user_id = current_user.id
end
end
我的路线包含:
resources :releases do
get :autocomplete_artist_name, :on => :collection
end
最后是艺术家领域:
<%= f.fields_for :artists do |builder| %>
<%= render 'artist_fields', :f => builder %>
<% end %>
(渲染的字段)
<%= f.label :name, "Artist" %><br />
<%= f.autocomplete_field :name, autocomplete_artist_name_releases_path, :class => "text" %>
答案 0 :(得分:0)
它显然可以满足您的需求。
我不想破坏你的观赏乐趣,但这一切都围绕着find_or_create_by
答案 1 :(得分:0)
你为什么不拿着艺术家的身份证 :id_element =&gt; f.autocomplete_field上的'#artist_id'? 如果artist_id param没有回来,你可以创建它