tomekfranek
tomekfranek

Reputation: 7109

What is the best known option to dynamically add model fields in nested form?

I have following nested form. And I want to add dynamically multiple web_profiles to person by clicking + button. Right now like you can see in the controller I can add only one web profile(@profile.person.web_profiles.build).

How would you implement that in the easiest way? Railscast #197 I think is not the simplest option.

Form View

= 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

Controller

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

Models

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

enter image description here

Upvotes: 1

Views: 164

Answers (2)

Sachin Singh
Sachin Singh

Reputation: 7225

Try using the nested_form gem by Ryan Bates

Upvotes: 1

Manoj Monga
Manoj Monga

Reputation: 3093

As you mentioned you are following nested form gem then you are just a few steps away to achieve this functionality.

Change your view code to look like:

 # 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'

Upvotes: 1

Related Questions