아티스트는 많은 이벤트가 있습니다. 이벤트에는 많은 아티스트가 있습니다. 이 두 모델 간의 조인을 성과라고합니다.find_or_create_by_name with has_many : through
나는 이벤트 추가/편집 페이지에서 아티스트를 이벤트와 연결하려고합니다. 존재하지 않는 경우에만 아티스트를 추가하고 관계없이 조인 (성능)을 만들 수 있기를 원합니다. 아티스트는 한 번만 이벤트와 연결되어야합니다.
accepts_nested_attributes_for 대신 find_or_create_by_name을 사용하는 것이 좋습니다.
가상 속성을 사용한다고하는 자동 완성에 대한 Railscasts # 102 지침을 따르고 있습니다. 나는 심지어 자동 완성 부분을 얻지 못했고, find_or_create_by_name을 작동 시키려고 노력했다.
이벤트 편집 및 새 페이지에서 "정의되지 않은 메서드 'artist_name'이 (가) # 개 발생했습니다. Railkeast에서 Ryan은 메서드를 모델에 추가하기 전에 정의되지 않은 메서드를 얻습니다. 하지만 모델에 메서드가 있습니다.
어떻게해야할지 모르겠다.
event.rb
validates_presence_of :name, :location
validates_uniqueness_of :name
validates_associated :performances
has_many :performances, :dependent => :delete_all
has_many :artists, :through => :performances
#accepts_nested_attributes_for :artists, :reject_if => proc {|a| a['name'].blank?}, :allow_destroy => true
def artist_name
artist.name if artist
end
def artist_name=(name)
self.artist = Artist.find_by_name(name) unless name.blank?
end
artist.rb
validates_presence_of :name
has_many :mixes
has_many :performances, :dependent => :delete_all
has_many :events, :through => :performances
events_controller.rb
belongs_to :artist
belongs_to :event
perfomance.rb
def create
@event = Event.new(params[:event])
respond_to do |format|
if @event.save
flash[:notice] = 'Event was successfully created.'
format.html { redirect_to(admin_events_url) }
format.xml { render :xml => @event, :status => :created, :location => @event }
else
format.html { render :action => "new" }
format.xml { render :xml => @event.errors, :status => :unprocessable_entity }
end
end
end
<p class="fields">
<%= f.label :artist_name, "Artist"%><br/>
<%= f.text_field :artist_name %>
<%= link_to_remove_fields "remove", f %>
</p>
에 그것은 당신이 당신이 얼마나 artist_fields.html.erb''에 제공 한 코드 부분에서 분명하지 않다 동안 폼 빌더 인스턴스 (f로 표시)를 설정합니다. 너는 과 같은 것이 있어야한다. <% form_for @event do | f | %> ... <% end %>'이들을 구분합니다. 그 맞습니까? – bjg
_artist_fields.html.rb는 부분입니다. form_for는 _form.html.rb에 있습니다. – shalako