次のネストされたフォームがあります。そして、ボタンをクリックして、動的に複数の web_profiles を person に追加したいと思い+
ます。現在、コントローラーでわかるように、追加できる Web プロファイルは 1 つだけです ( @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