How to use Mixin and ActiveRecord:Base together
Consider this simple application in RUby on Rails:
Student & Teacher extends Person. Person has 2 properties, name & age. Student has 1 extra property, grade. Teacher has 1 extra property, salary.
I want to store开发者_如何学Python the student & teacher information in separate db tables. I want to take advantage of RoR's utility class ActiveRecord:Base
to retrive data for these models. Because Person
is not expected to be instantiated, I can mix it with Student
& Teacher
as follows:
class Student < ActiveRecord:Base
include Person
end
module Person
end
Question:
- Is this the correct way of implementation?
- How to implement this without creating a databse table called
persons
? I only want to generate 2 tables, namelystudents
andteachers
, and both should have the 3 properties mentioned above.
Person does not have to be a model - it can be a library/module (which you then mixin as per your example). You'd keep that in RAILS_ROOT/lib. Your Student and Teacher classes can be models (which use AR::Base), and the person can just be a bunch of common methods used by both.
Alternatively, if your child class is far more complicated - look into "Single table inheritance" - the description of which is beyond the scope of this answer... but you can google for it.
精彩评论