1

次のネストされたフォームがあります。そして、ボタンをクリックして、動的に複数の 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

ここに画像の説明を入力

4

2 に答える 2

1

あなたが述べたように、ネストされたフォームの宝石に従っているので、この機能を実現するのはほんの数歩です。

ビュー コードを次のように変更します。

 # 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'
于 2013-06-13T12:22:38.597 に答える
1

Ryan Batesによる nested_form gemを使ってみてください

于 2013-06-13T12:26:46.820 に答える