accepted_nested_attributes_for with has_many =>:通过选项

我有两个模型,链接和标签,通过第三个link_tags关联。 以下代码位于我的链接模型中。

协会:

class Link  :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  :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中的代码:

  account_links_path do |f| %>  "form", :locals => { :f => f } %>  

和相应的部分:

   



Tags

链接控制器中的create action中的以下代码行引发错误:

 @link = @current_user.links.build(params[:link]) 

错误: Tag(#-621698598) expected, got Array(#-609734898)

has_many =>中是否还需要其他步骤:通过案例? 这些似乎是基本has_many案例的唯一指示变化。

看看你的代码行

 <% f.fields_for :tags_attributes do |tag_form| %> 

您只需使用:tags而不是:tags_attributes 。 这将解决您的问题

确保您在控制器中构建了链接和标签

 def new @link = @current_user.links.build @link.tags.build end 

我在stackoverflow上找到了这个:

Rails嵌套表单与has_many:through,如何编辑连接模型的属性?

请告诉我它是否有效。

为了使其工作,您需要传入正确的参数哈希:

 params = { :link => { :tags_attributes => [ {:tag_one_attr => ...}, {:tag_two_attr => ...} ], :link_attr => ... } } 

你的控制器看起来像:

 def create @link = Link.create(params[:link]) # this will automatically build the rest for your end 

试试这个:

 <% f.fields_for :tags_attributes do |tag_form| %> 

在新操作的控制器中(加载表单部分),您是否通过链接构建@tag?

所以你应该看到以下内容:

 @link = Link.new @tag = @link.tags.build 

最好发布新的内容并创建links_controller的动作。

尝试

 <% f.fields_for :tags do |tag_form| %> 

(即丢失_attributes in:tag_attributes)这就是我通常做嵌套表单的方式

您需要在控制器或视图中构建标记

 def new @link = @current_user.links.build @link.tags.build end #in your view you can just use the association name <% f.fields_for :tags do |tag_form| %>