[英]What is the best known option to dynamically add model fields in nested form?
我有以下嵌套形式。 我想通过单击+
按钮将多个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
正如您提到的那样,您正在遵循嵌套形式的 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 '[—]'.html_safe, :title => 'Remove Profile'
= f.link_to_add '[+]'.html_safe, :web_profiles, :title => 'Add a new Profile'
尝试使用Ryan Bates的nested_form gem
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.