accepted_nested_attributes_for with has_many =>:通过选项

And*_*w C 26 ruby-on-rails has-many-through nested-attributes

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

协会:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

查看来自new.html.erb的代码:

<% form_for [current_user, @link], :url => account_links_path do |f| %>
<%= render :partial => "form", :locals => { :f => f } %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

和相应的部分:

  <%= 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>
Run Code Online (Sandbox Code Playgroud)

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

@link = @current_user.links.build(params[:link])
Run Code Online (Sandbox Code Playgroud)

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

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

Jyo*_*thu 8

看看你的代码行

<% f.fields_for :tags_attributes do |tag_form| %>
Run Code Online (Sandbox Code Playgroud)

你需要使用:tags而不是:tags_attributes.这将解决您的问题

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

def new
  @link = @current_user.links.build
  @link.tags.build
end
Run Code Online (Sandbox Code Playgroud)


Tia*_*ago 5

我在stackoverflow上找到了这个:

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

请告诉我它是否有效.

  • 这是我的问题(也是我的答案),我可以肯定地告诉你它有效:) (2认同)

小智 1

尝试这个:

<% f.fields_for :tags_attributes do |tag_form| %>
Run Code Online (Sandbox Code Playgroud)