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 

,332 10

답변

1

당신이 언급 한대로 nested form 보석을 따라 가면이 기능을 구현할 수 있습니다.

# 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

라이언하여 nested_form 보석을 사용해보십시오 베이츠

:

는 모습을보기 코드를 변경