Polymorphic form

I have two partials to deal with contact information. The Contact
information uses single-table polymorphism. I want to be able to use
save on Contact and set ‘type’ manually, based on the type of form the
user is filling in. This is saved as the value on a hidden field.

class Contact
belongs_to :person
acts_as_list :scope => :person
validates_presence_of :type
validates_inclusion_of :type, :in => TYPES.map {|disp, val| val}
validates_presence_of :label

class PhoneNumber < Contact

validates_as_phone_number :value
validates_presence_of :value
validates_uniqueness_of :value, :scope => [:person_id, :type]

class Address < Contact
validates_presence_of :zip_addon_id
validates_uniqueness_of :value, :scope => [:person_id, :type]
belongs_to :zip_addon

Here’s one of the partials:

<% fields_for "person[contacts][]", phone_number do |contact_form| - %>

Phone Number
<%= contact_form.hidden_field :type %>
<%= contact_form.select :label, PhoneNumber::LABELS, :selected => PhoneNumber::LABELS.first %> Area + Phone <%= contact_form.text_field :value %>
<%= remove_contact_link :phone_number, 'remove' %>

<% end -%>

Everything else gets saved just fine, but it complains on validation
about the lack of a type field:

  • Person contacts type can’t be blank

I have it saving like so, in users_controller.rb
def create
@user = User.new(params[:user])
@person = @user.build_person(params[:user][:person])
@person.contacts_attributes = params[:person][:contacts]
if @user.save
flash[:notice] = ‘User was successfully registered.’
redirect_back_or_default account_url
render :action => :new

Note also that when I view source on the new user page, the type value
is apparently set appropriately.

Thanks so much.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs