我有以下嵌套形式。我想通过单击+
按钮向人员动态添加多个 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