Rails 3 中的类表继承 [英] Class Table Inheritance in Rails 3

查看:37
本文介绍了Rails 3 中的类表继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个 Rails 3 应用程序,它看起来可能需要对几个模型使用类表继承.

I'm currently working on a Rails 3 application that looks like it might need to use Class Table Inheritance for a couple of models.

正在发生的事情的一个简化示例是这样的.

A simplified example of what's going on is this.

我有一个名为 Person 的类,具有通用属性,如姓名、电子邮件、密码,这些属性对于应用程序中的所有类型的人都是通用的,用于身份验证.

I have a class called Person with general attributes like name, email, password which are common to all types of people in the application and used for authentication.

Person(或两种类型的人...)有两个子类,Driver 和Passenger.这两个子类共享 Person 的通用属性,但又具有它们自己独有的特定附加属性.(例如,司机可以拥有许多车辆和执照,但乘客不会)

There are two subclasses to Person (or two types of people...), Driver and Passenger. Both of these subclasses share the generic attributes of Person but then have specific additional attributes which are unique to themselves. (for example a Driver can have many Vehicles and Licenses but a Passenger would not)

对于这种情况,我将如何实施 CTI?我一直在查看此处提供的示例:

How would I implement CTI for this kind of situation? I've been looking at an example provided here:

http://rhnh.net/2010/08/15/class-table-inheritance-and-eager-loading

但它没有推测如何从 Driver 或Passenger 对象访问Person 的通用属性,我对此感到有些困惑.

But it doesn't speculate on how to access the common attributes of a Person from a Driver or Passenger object and I'm a bit confused by that.

特别是,我想知道的是:

In particular, what I'd like to know is:

如果我要更新驱动程序的属性,如何轻松访问和更新父人员表上的相关属性?我是否必须挂钩 after_save 回调并分离出哪个属性更新去哪里?或者有没有更好的方法来解决这个问题?

If I'm updating the attributes of a Driver, how can I easily access and update the relevant attributes on the parent people table? Do I have to hook into an after_save callback and separate out which attribute update goes where? Or is there a better way to approach this?

推荐答案

还有一个插件 'acts_as_relation' 可以做到这一点,
https://github.com/hzamani/acts_as_relation/

Also there is a plugin 'acts_as_relation' to do this,
https://github.com/hzamani/acts_as_relation/

在你的情况下,代码是这样的:

in your case the code will be this:

class Driver < ActiveRecord::Base
   acts_as :person
end

class Passenger < ActiveRecord::Base
  acts_as :person
end

不要忘记将 person_typeperson_id 列添加到 persons 表中.
现在 Drive 和Passenger 都继承了Person 属性、验证和方法.

Don't forget to add person_type and person_id columns to persons table.
Now both Drive and Passenger inherit Person attributes, validations and methods.

这篇关于Rails 3 中的类表继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆