accept_nested_attributes_for with has_many =>: through Options

Ich habe zwei Modelle, Links und Tags, die durch ein drittes, link_tags, verbunden sind. Der folgende Code ist in meinem Link-Modell.

Verbände:

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 Aktionen:

  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

Code aus new.html.erb anzeigen:

<% form_for [current_user, @link], :url => account_links_path do |f| %>
<%= render :partial => "form", :locals => { :f => f } %>
<% end %>

Und der entsprechende Teil:

  <%= 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>

Die folgende Codezeile in der Aktion create im Link-Controller löst einen Fehler aus:

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

Der Fehler:Tag(#-621698598) expected, got Array(#-609734898)

Sind im has_many =>: through-Fall zusätzliche Schritte erforderlich? Dies scheinen die einzigen angezeigten Änderungen für den Basisfall has_many zu sein.

Antworten auf die Frage(7)

Ihre Antwort auf die Frage