# Polymorphic form

**URL:** <https://www.ruby-forum.com/t/polymorphic-form/175866>\
**Category:** Rails\
**Created:** [September 21, 2009, 7:57pm UTC](https://www.ruby-forum.com/t/polymorphic-form/175866 "2009-09-21T19:57:02Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![princenamor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c0e974/32.png) [@princenamor](https://www.ruby-forum.com/u/princenamor)\
**Post date:** [September 21, 2009, 7:57pm UTC](https://www.ruby-forum.com/t/polymorphic-form/175866/1 "2009-09-21T19:57:02Z")

</div>

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  
end

class PhoneNumber \< Contact

# 

# …

# 

validates\_as\_phone\_number :value  
validates\_presence\_of :value  
validates\_uniqueness\_of :value, :scope =\> [:person\_id, :type]  
end

class Address \< Contact  
validates\_presence\_of :zip\_addon\_id  
validates\_uniqueness\_of :value, :scope =\> [:person\_id, :type]  
belongs\_to :zip\_addon  
end

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  
else  
render :action =\> :new  
end  
end

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

Thanks so much.

John
