开发者

How to use Mixin and ActiveRecord:Base together

开发者 https://www.devze.com 2023-03-16 01:19 出处:网络
Consider this simple application in RUby on Rails: Student & Teacher extends Person. Person has 2 properties,name & age.

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:

  1. Is this the correct way of implementation?
  2. How to implement this without creating a databse table called persons? I only want to generate 2 tables, namely students and teachers, 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消