以嵌套形式动态添加模型字段的最佳选择是什么?

时间:2013-06-13 11:43:41

标签: ruby-on-rails ruby ruby-on-rails-3 nested-forms nested-attributes

我有以下嵌套表格。我想通过点击+按钮动态地向用户添加多个web_profiles。就像您在控制器中看到的那样,我只能添加一个Web配置文件(@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

enter image description here

2 个答案:

答案 0 :(得分:1)

正如您所提到的,您正在关注nested form 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'

答案 1 :(得分:1)

尝试使用Ryan Bates的nested_form宝石