Let’s say I have a person table, and I want it to classify all people as either alphas or omegas. All omegas have exactly one alpha but no omegas, all alphas have any number of omegas but no alpha.
This is a simple two level hierarchy, which I can encode using a single foreign key:
CREATE TABLE people (
id INTEGER NOT NULL PRIMARY KEY,
alpha_id INTEGER FOREIGN KEY REFERENCES people,
-- alpha_id is NULL if and only if this person is an alpha
-- other stuff we know about people...
);
Now I can create a general person class, but it gets slightly awkward when I get to the alpha-omega relationship.
class Person < ActiveRecord::Base
# ... stuff I know about people
# if alpha_id is NULL
has_many :omegas, :as => :alpha, :class_name => Person
# else
belongs_to :alpha, :class_name => Person
end
It’d be nice to split the person off into two subclasses, one for Alphas, one for Omegas, but I’m not sure how well that’d play with ActiveRecord.
Ideally, I’d like something like this:
class Person < ActiveRecord::Base
# ... stuff I know about people
end
class Alpha < Subset(Person)
column_is_null :alpha_id
has_many :omegas
end
class Omega < Subset(Person)
column_is_not_null :alpha_id
belongs_to :alpha
end
Is this sort of subclassing, or something approximating it, available in ActiveRecord?
Use named_scope:
Now you can reference Person.alphas and Person.omegas to get the objects you are looking for. Does this help?