Mapping active record objects to virtual attributes

I've got a phone number field defined in a model as a single String. However, the form used to input the phone number exposes the number as three distinct fields to help the user enter the number in the correct format. I'm mapping the three input parameters to the single string in a before_validation method which seems to work fine, but I want to be able to map the single string to the three distinct fields when the record is loaded from the database. What's the correct hook to do that? I tried to provide a phone_number= method that used self[:phone_number]=... to assign the attribute and then split the phone number up into the three fields to be returned by accessors, but AR doesn't seem to call this method when the record is loaded from the database. What's the best way to accomplish this?

class MyModel < ActiveRecord::Base

  .....

  def after_find       # call your method to split the phone number here   end

Another way to do this is with a virtual accessors

  def area_code       phone_number[0..2]   end

  def area_code=(area_code)      raise ArgumentError.new('invalid area code') unless area_code.length == 3      phone_number[0..2] = area_code   end

of course this will differ depending just how you represent the numbers.

Rick Denatale wrote: