views:

29

answers:

1

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.5555x234, 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?

+2  A: 

I normally do this as a before_save:

before_save :update_phone_number

def update_phone_number
  self.phone_number = [area_code, first_three_digits, second_four_digits, extension].reject(&:blank?).join('.')
end

First I would have some validations:

validates_presence_of :area_code, :first_three_digits, :second_four_digits
validates_format_of :area_code, :with => /\d{3}/
validates_format_of :first_three_digits, :with => /\d{3}/
validates_format_of :second_four_digits, :with => /\d{4}/
validates_format_of :extension, :with => /\d{0,6}/, :allow_blank => true

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:

attr_accessor :area_code, :first_three_digits, :second_four_digits, :extension
Geoff Lanotte
My phone extension is 4 digits, and at my school it is 5 digits. Maybe it should be a range `{0,6}` ?
webdestroya
good call, that would likely need to be a bit more flexible
Geoff Lanotte
Geoff, you have been my saving grace the last few days! Haha, thanks for all the help man, I really appreciate it.It looks like, with this approach you have the area_code, first_three_digits, second_four_digits, etc as entries in your migration, along with a phone_number field that joins all the other fields. Can I handle this operation while only have the phone_number column in my table and leaving out the area_code, etc columns. This way I'm not storing unnecessary data, but still have the separate text_fields in my view?
Bradley Herman
ah, yes this approach works without the area_code, etc being columns. You can apply validations to any attribute in a model. I added the line to add the attr_accessors to the model.
Geoff Lanotte