0
votes

I would like a little confirmation that I'm doing this correctly. Using rails single table inheritance I have the following models and class method:

class PhoneNumber < ActiveRecord::Base
  def self.qual?(number)
    klass = self
    klass.exists?(:phone_number => phone_number)
  end
end

class Bubba < PhoneNumber
end

class Rufus < PhoneNumber
end

Bubba.qual?("8005551212")

Tests pass and everything seems to work properly in rails console. Just wanted to confirm that I'm not headed for future trouble by using self in the superclass PhoneNumber and using that to execute class methods on subclasses from the parent.

Is there a better way?

1

1 Answers

1
votes

Looks okay to me. You can shorten the method further:

class PhoneNumber < ActiveRecord::Base
  def self.qual?(phone_number)
    exists?(:phone_number => phone_number)
  end
end

Mindful of the this bug in STI if you override the qual? method in the child classes.

Edit

Invoking qual? method:

# out side your STI models
Bubba.qual?("8003455678")
Rufus.qual?("8003455678")
PhoneNumber.qual?("8003455678")

# in the class method of your STI model
qual?("8003455678")

# in the instance method of your STI model
self.class.qual?("8003455678")