Jump to content

The ultimate community for Ruby on Rails developers.


Optional nested form


  • Please log in to reply
1 reply to this topic

#1 gel87



  • Members
  • 1 posts

Posted 03 April 2014 - 06:22 AM

Dear all,


I've this models:

class Club < ActiveRecord::Base
    has_one :address, as: :addressable
    belongs_to :person
    accepts_nested_attributes_for :address

class Address < ActiveRecord::Base
    belongs_to :addressable, polymorphic: true

class Person < ActiveRecord::Base
    has_many :club
    has_one :address, as: :addressable

Now I want to create/edit a club and either enter an adress for my club or select a person who represents the club address. Therefore I need a select field in my form to switch if the club will have his own address or use the address of the person. Depending on the selection the nested form or the person select box should be disabled and in addition NO relation to address from club should be created.



#2 Lauree



  • Members
  • 6 posts
  • LocationNew York

Posted 23 May 2014 - 07:01 AM


You need to have a form containing nested fields for address and also a select list for person object. Please consider following example form for club :

= form_for @club do |f| 
  = select_tag 'select_association', options_for_select([['Person',  'person'], ['Address', 'address']]) 
  = fields_for :address do |addr| 
    / nested fields for address object will go here. 
  = f.select :person_id, options_from_collection_for_select(@people,  "id", "name"), include_blank: true 

And in JS/JQuery you need to disable the input fields or select lists depending on the option selected in select_association select list as :

  if($(this).val() == 'person'){ 
    $("input[id *= 'address_attributes']").prop('disabled', true); 
  } else if($(this).val() == 'address') { 
    $('select#club_person_id').prop('disabled', true); 


Above code will disable the fields that are not required depending upon the selection of select_association.

The disabled fields will not be sent by Browser in Params and you will have only fields that you need i.e. you will have either person_id or nested field for the address attributes.




Hire skilled Ruby on Rails Developer

Check out Ruby on Rails Outsourcing Services by Allerin

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users