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:
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' %>
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