我有兩個模型,鏈接和標籤,通過第三個link_tags相關聯。以下代碼位於我的Link模型中。accepted_nested_attributes_for has_many =>:通過選項
協會:
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操作:
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
查看代碼從new.html.erb:
<% 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>
下面的代碼行,在鏈路控制器的創建動作引發錯誤:
@link = @current_user.links.build(params[:link])
錯誤:Tag(#-621698598) expected, got Array(#-609734898)
是否有在的has_many需要額外的步驟=>:通過案例?這些似乎是基本哈薩克斯坦案例中唯一顯示的變化。在新的行動(即加載形式部分),你建立通過你的鏈接@tag
<% f.fields_for :tags_attributes do |tag_form| %>
我無法根據您發佈的代碼重現您的問題。你可以發佈你的三個模型的關聯部分(has_many/belongs_to/etc行),這兩個相關的控制器動作(鏈接#新,鏈接#創建)以及任何與鏈接形式有關的視圖代碼。 – EmFi 2010-02-06 15:52:04
我已經添加了關聯,控制器操作和視圖的代碼。謝謝你的幫助。現在 – 2010-02-06 19:33:16