Let’s say i have a class with a lot of functionality, called Person. It
happens that men and women are treated differently within my app and i’m
sick of passing
:condition => ["gender = ? ", F]
all the time for cases dealing with women. Instead, i want to make two
new classes, Man and Woman, which inherit all the functionality of
Person but only some of the records, based on the above condition.
Can anyone tell me the syntax for this please? I know how to extend a
class but not to limit it in this way.
two
new classes, Man and Woman, which inherit all the functionality of
Person but only some of the records, based on the above condition.
Can anyone tell me the syntax for this please? I know how to extend a
class but not to limit it in this way.
Sounds like you want single table inheritance:
Keep your existing Person class, with all the common code, and add a
string column called ‘type’ to the table
Now create classes Man and Woman that inherit from Person.
Now whenever you do somethine like Man.find :all, or has_many :women
etc… it will be scoped to Man or Woman as appropriate. You can still
go Person.find :all to get everyone.
If you already have existing data, you’ll need to populate the newly
created type column with the name of the appropriate subclass of Person.
two
new classes, Man and Woman, which inherit all the functionality of
Person but only some of the records, based on the above condition.
Can anyone tell me the syntax for this please? I know how to extend a
class but not to limit it in this way.
Sounds like you want single table inheritance:
Keep your existing Person class, with all the common code, and add a
string column called ‘type’ to the table
Now create classes Man and Woman that inherit from Person.
Now whenever you do somethine like Man.find :all, or has_many :women
etc… it will be scoped to Man or Woman as appropriate. You can still
go Person.find :all to get everyone.
If you already have existing data, you’ll need to populate the newly
created type column with the name of the appropriate subclass of Person.
Fred
Ah, “single table inheritance” - i’d wondered before what that was, now
i know the answer
Perfect, thanks!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.