开发者

Rails ActiveRecord Question

开发者 https://www.devze.com 2023-01-14 01:19 出处:网络
Single Table Inheritance using ActiveRecord. Since we can use @test = Employee.all and find all the employees created. How does rails do this? Since we only use a User Table. How does it know about em

Single Table Inheritance using ActiveRecord. Since we can use @test = Employee.all and find all the employees created. How does rails do this? Since we only use a User Table. How does it know about employees and retrieve only employees? Rails Magic? Explanation anyone? Thank you in advance.

Base Class : Person (inherits ActiveRecord)
Sub-Class: Employee, Supervisor, Manager (each inherit Person)

So my Person table needs to have a _type and _id field to make the table polymorphic.

My next question is how开发者_开发百科 do I get Employee Associated to the Person table and when you save an employee, how do you get it to actually put in Employee in the person_type field?


To indicate to Ruby on Rails that the users table needs to support Single Table Inheritance you need to add a column named ‘type’ to the users table. Here is my users table definition:

CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, user VARCHAR(15) NOT NULL UNIQUE, pass VARCHAR(40) NOT NULL, type VARCHAR(20) NOT NULL, PRIMARY KEY (id) );

In the column named type you should store the name of the class, the class type, that should be used for each user. To mark an certain user as an admin set his type to ‘Administrator’. By setting a user’s type to ‘Administrator’ you are giving him full administrator privileges as defined in your Administrator model class.

http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/


Single table inheritance uses a type column on the table to indicate the type of the object. ActiveRecord knows that your Employee class is using single table inheritance (it has no matching table and the users/people table has a type column).

So when you ask for Employee.all it knows to looks for all entries in the users/people table where type == 'Employee'.

If you look at the logs the SQL will be displayed for these queries and you'll see the 'magic' happening.

0

精彩评论

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