3

我正在尝试构建用于添加议程的复杂表单,并且我想使用link_to_add helper动态地为表单中的给定议程添加新用户。使用nested_form宝石和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 %>

一切正常,除了不附加fields_for :user块的link_to_add。如何使 link_to_add 助手与fields_for :roles块一起渲染整个fields_for :user块?

4

1 回答 1

0

我添加了一个新补丁,使这个答案与最新版本的nested_form 相关。现在使用这个为我工作..

于 2013-11-01T23:29:57.943 回答