두 번째 모델 인 link_tag와 link_tags가 있습니다. 다음 코드는 내 링크 모델에 있습니다.has_many => : with 옵션을 사용하여 accepts_nested_attributes_for을 입력하십시오.
협회 : new.html.erb에서
def new
@link = @current_user.links.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @link }
end
end
def create
@link = @current_user.links.build(params[:link])
respond_to do |format|
if @link.save
flash[:notice] = 'Link was successfully created.'
format.html { redirect_to links_path }
format.xml { render :xml => @link, :status => :created, :location => @link }
else
format.html { render :action => "new" }
format.xml { render :xml => @link.errors, :status => :unprocessable_entity }
end
end
end
보기 코드 :
class Link < ActiveRecord::Base
has_many :tags, :through => :link_tags
has_many :link_tags
accepts_nested_attributes_for :tags, :allow_destroy => :false,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
class Tag < ActiveRecord::Base
has_many :links, :through => :link_tags
has_many :link_tags
end
class LinkTag < ActiveRecord::Base
belongs_to :link
belongs_to :tag
end
links_controller 작업
<% form_for [current_user, @link], :url => account_links_path do |f| %>
<%= render :partial => "form", :locals => { :f => f } %>
<% end %>
그리고 해당 부분 :
<%= f.error_messages %>
<p>
<%= f.label :uri %><br />
<%= f.text_field :uri %>
</p>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<h2>Tags</h2>
<% f.fields_for :tags_attributes do |tag_form| %>
<p>
<%= tag_form.label :name, 'Tag:' %>
<%= tag_form.text_field :name %>
</p>
<% unless tag_form.object.nil? || tag_form.object.new_record? %>
<p>
<%= tag_form.label :_delete, 'Remove:' %>
<%= tag_form.check_box :_delete %>
</p>
<% end %>
<% end %>
<p>
<%= f.submit 'Update' %>
</p>
링크 컨트롤러에서 생성 행동 16,
다음의 코드는, 에러가 발생합니다 :
@link = @current_user.links.build(params[:link])
오류 : Tag(#-621698598) expected, got Array(#-609734898)
이 has_many에 필요한 추가 단계가 있습니다 => : 사건을 통해? 이것들은 기본 has_many 경우에 대해 유일한 변경 사항 인 것 같습니다.
같은 컨트롤러에 연결 및 태그 구축이 있는지 확인 문제가 해결됩니다. 3 가지 모델의 연관 부품 (has_many/belongs_to/etc 라인)을 게시 할 수 있습니까? 관련 컨트롤러 액션 (links # new, links # create)과 링크 양식과 관련된 모든보기 코드. – EmFi
연관, 컨트롤러 작업 및보기에 대한 코드를 추가했습니다. 당신의 도움을 주셔서 감사합니다. 지금 –