I have a Phone model for phone numbers in my application thats built as follows:
t.column :number, :string
t.references :phoneable, :polymorphic => true
I want to restrict the number to be of the format 317.555.5555×234, so I’m creating a form with four boxes (area code, 3 digits, 4 digits, ext):
- form_for @user do |user_form|
-user_form.fields_for :phones do |phone|
= phone.text_field :area_code
= phone.text_field :first_three_digits
etc...
I’m assuming a virtual attribute would be the route to go (a la railscasts ep16), but not sure how to assemble the “number” from the 4 separate text_fields.
I think I would have to do something like this:
def full_number=(phone)
self.number = area_code+"."+first_three_digits+"."+second_four_digits+"."+extension
end
But I’m unsure of how to approach this in assembling the number from form inputs. Any thoughts?
I normally do this as a before_save:
First I would have some validations:
This is just to make sure that you get valid data in your phone number and your before save doesn’t throw any errors. I also assumed that you would allow the extension to be blank, but is easily changed.
EDIT: you will want to have attr_accessors for the different segments of the phone number: