开发者

Virtual Attributes & Rails

开发者 https://www.devze.com 2023-01-08 21:42 出处:网络
I have a Phone model for phone numbers in my application thats built as follows: t.column:number,:string

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+"."开发者_C百科+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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消