Подтвердить что ты не робот

Accepts_nested_attributes_for с has_many =>: через параметры

У меня есть две модели, ссылки и теги, связанные через третье, link_tags. Следующий код находится в моей модели Link.

Ассоциация:

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>

Следующая строка кода в действии create в контроллере Link вызывает ошибку:

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

Ошибка: Tag(#-621698598) expected, got Array(#-609734898)

Есть ли дополнительные шаги в has_many = > : через case? Кажется, это единственные указанные изменения для основного случая has_many.

4b9b3361

Ответ 1

Взгляните на строку вашего кода

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

Вам нужно использовать только :tags вместо :tags_attributes. Это решит вашу проблему.

Убедитесь, что вы создали ссылки и теги в своем контроллере, например

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

Ответ 3

Для того, чтобы это сработало, вам нужно передать в хеш правильных параметров:

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

Ответ 4

Попробуйте следующее:

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

Ответ 5

В вашем контроллере в новом действии (который загружает форму частично) вы строите @tag по вашей ссылке?

Итак, вы должны увидеть что-то вроде строк:

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

Лучше всего разместить содержимое нового и создать действие вашего link_controller.

Ответ 6

попробовать

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

(т.е. потерять _трибуты в: tag_attributes). Как я обычно делал вложенные формы

Ответ 7

Вам нужно создать тег в своем контроллере или в представлении

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