0

I have a PhoneNumber class (below) that I want to act as the parent class to child classes using single table inheritance. These children include MobileNumber, HomeNumber, Fax, Pager, etc. I would like to force every PhoneNumber class to be a child class of PhoneNumber. How can I do this? I would appreciate any help!

class PhoneNumber < ActiveRecord::Base

    attr_accessible :number, :user_id

    before_save :format_number

    belongs_to :user

    validates_presence_of :number
    validates_presence_of :user_id

    def format_number
        number.gsub!(/\D/, '')
    end
end
  • This is what modules are for. You're defining an abstract class which is really just a set of behaviors for the other things in your system that you want to act like phone numbers. – jdl Jul 02 '13 at 19:31
  • I'm not sure I understand the question. The title doesn't seem to bear much relation to the content, and you've indicated that you already know about Single Table Inheritance. So what is it that you're trying to accomplish that STI doesn't do? – gregates Jul 02 '13 at 19:34
  • I think he's trying to prohibit someone from calling `PhoneNumber.new`, and instead to only instantiate one of the subclasses. Which is why I'm saying "make PhoneNumber a module and then no one can call .new on it". – jdl Jul 02 '13 at 19:39
  • Sorry for being unclear, what I mean is I would like to make the parent class PhoneNumber unusable (uncreatable) so that only its child classes can be created. I'm not sure a module would work...I would like to be able to call PhoneNumber.all and have all numbers listed for me (fax, pager, home, etc.). – philjay Jul 02 '13 at 20:00
  • possible duplicate of [Rails STI - Prevent base class from instantiation](http://stackoverflow.com/questions/2850418/rails-sti-prevent-base-class-from-instantiation) – Shadwell Jul 02 '13 at 20:22
  • Yeah it's the same issue. I was able to get it working from that. – philjay Jul 02 '13 at 20:39

0 Answers0