1

我有以下嵌套形式。我想通过单击+按钮向人员动态添加多个 web_profiles。现在就像您在控制器中看到的那样,我只能添加一个网络配置文件(@profile.person.web_profiles.build)。

你将如何以最简单的方式实现它?Railscast #197我认为这不是最简单的选择。

表单视图

= simple_form_for @profile do |pr|
  = pr.fields_for :person do |pe|
    = pe.input :first_name
    = pe.fields_for :web_profiles do |w|
      = w.input :name

控制器

class ProfilesController < ApplicationController
  def new
    @profile = Profile.new
    @profile.person = Person.new
    @profile.person.web_profiles.build
  end

  def create
    @profile_form = ProfileForm.new
    if @profile_form.submit(params[:profile_form])
      redirect_to @profile_form.profile, notice: 'Profile was successfully created.'
    else
      render action: "new"
    end
  end
  ...
end

楷模

class Profile < ActiveRecord::Base
  attr_accessible :overall_rating, :person_id, :person_attributes
  belongs_to  :person
  accepts_nested_attributes_for :person
  delegate :first_name, :last_name, to: :person
end

class Person < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :web_profiles_attributes
  has_one     :profile
  has_many    :web_profiles, class_name: "ContactType::WebProfile"

  accepts_nested_attributes_for :web_profiles, allow_destroy: true
end

class ContactType::WebProfile < ActiveRecord::Base
  attr_accessible :name, :person_id

  belongs_to :person
end

在此处输入图像描述

4

2 回答 2

1

正如您所提到的,您正在遵循嵌套表单gem,那么您只需几步即可实现此功能。

将您的视图代码更改为如下所示:

 # create form using simple_nested_form builder as it is required while using nested form along with simple form.
 = simple_nested_form_for @profile do |pr|
   = pr.fields_for :person do |pe|
     = pe.input :first_name
       = pe.fields_for :web_profiles do |w|
         = w.input :name
         # link_to_remove adds the link that removes the newly added fields.
         = w.link_to_remove '[&mdash;]'.html_safe, :title => 'Remove Profile'
       = f.link_to_add '[+]'.html_safe, :web_profiles, :title => 'Add a new Profile'
于 2013-06-13T12:22:38.597 回答
1

尝试使用Ryan Bates的nested_form gem

于 2013-06-13T12:26:46.820 回答