Lets say I have three Classes
Person::Single < Person
Person::Married < Person
Lets say I have two Persons that are Single =>
Then i get two Persons when I do:
But my goal is to get only the persons that are type
Person and not
What I tried is:
but this also returns
Person::Married inherit from
What can I do instead? Is there for example an way to say that
::Married have the same methods from
person but are not the same type? Thanks
Best How To :
Since this is marked with the rails tag, I assume your Person class is an ActiveRecord model. There is some more information missing, but I will just assume where I don't really know ;)
Your Person class inherits the ActiveRecord methods, for example "all", and Person::Single (and ::Maried) will inherit it through Person.
So, naturally, when you do a Person.all it will just do the regular <#ActiveRecord>.all method, which does not know and not care about ::Single and ::Maried.
What you can do is dynamically setting the default_scope, based on the class name of which you are calling .all, or .where or whatever on.
class Person < ActiveRecord::Base
scope = if self.name == Person.sti_name
where(:type => Person.sti_name)
This will also scope your where(:whatever => x) queries.
However, this is asuming you have an attribute called "type" for you Person model (column in database).
EDIT: As Holger pointed out, there is already magic involved with rails STI. I still think it is viable to set a default scope, only you should skip setting the scopes for single and married. If you don't need it as a default scope, you should just try
Person.where(:type => Person.sti_name) or
Person.where(:type => Person.name) since rails asserts the class name to sti_name if the class inherits from ActiveRecord::Base.