我有两个模型,链接和标签,通过第三个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