rails与嵌套表单link_to_add之间的多对多关系不起作用

时间:2013-08-15 18:47:36

标签: ruby-on-rails nested-forms

我正在尝试构建用于添加Agendas的复杂表单,并且我想使用link_to_add helper动态地为表单中的给定议程添加新用户。使用nested_form gem和accepts_nested_attributes_for方法。这些是我的模特:

class Agenda < ActiveRecord::Base
  has_many :roles
  has_many :users, through: :roles
  accepts_nested_attributes_for :roles

  belongs_to :owner, class_name: User

  attr_accessible :name,
                  :address,
                  :owner,
                  :roles_attributes

end


class Role < ActiveRecord::Base
  belongs_to :agenda
  belongs_to :user
  accepts_nested_attributes_for :user

  attr_accessible :agenda,
                  :role,
                  :user

end

class User < ActiveRecord::Base
  has_many :roles
  has_many :agendas, through: :roles
end

和我的控制员:

class AgendasController < ApplicationController

  ...

  def new
    @agenda = Agenda.new
    @role = @agenda.roles.build
    @user = @role.build_user
  end
end

和我的表格:

<%= nested_form_for @agenda do |f| %>
  ....
  <%= f.fields_for :roles do |role_f| %>
    <%= role_f.fields_for :user do |user_f| %>
      <div class="control-group">
        <%= user_f.label :email, :class=>"control-label" %>
        <div class="controls controls-row">
          <%= user_f.text_field :email %>
        </div>
      </div>
    <% end %>
    <div class="control-group">
      <%= role_f.label :role, :class=>"control-label" %>
      <div class="controls controls-row">
        <%= role_f.text_field :role %>
      </div>
    </div>
    <%= role_f.link_to_remove "Remove user" %>
  <% end %>
  <%= f.link_to_add "Add new users", :roles %>

<% end %>

一切正常,但link_to_add除外,它不会附加fields_for :user块。如何使link_to_add帮助器与fields_for :roles块一起呈现整个fields_for :user块?

1 个答案:

答案 0 :(得分:0)

我添加了一个新补丁,使this answer与最新版本的嵌套表单相关。现在可以使用这个..