如何在Ruby on Rails中实现Active Record继承? [英] How to implement Active Record inheritance in Ruby on Rails?

查看:302
本文介绍了如何在Ruby on Rails中实现Active Record继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用活动记录实现继承?

How to implement inheritance with active records?

例如,我想要一个类Animal,Dog类和Cat类。

For example, I want a class Animal, class Dog, and class Cat.

Rails如何支持单表继承。

How would the model and the database table mapping be?

推荐答案

AR文档< a>:

From the AR docs:


Active Record允许通过
继承,将类的名称存储在默认的
列中被命名为type
(可以通过覆盖
Base.inheritance_column来改变)。这意味着
的继承看起来像这样:

Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:

class Company < ActiveRecord::Base; end   
class Firm < Company; end  
class Client < Company; end   
class PriorityClient < Client; end



当您执行Firm.create(:name =>
37signals此记录将
保存在公司表中,类型为
=Firm。然后,您可以使用Company.find(:first,name
='37signals')再次获取此行,它将返回Firm对象。

When you do Firm.create(:name => "37signals"), this record will be saved in the companies table with type = "Firm". You can then fetch this row again using Company.find(:first, "name = ‘37signals’") and it will return a Firm object.

如果你的表中没有定义类型列
,单表
继承不会被触发。在
这种情况​​下,它将像普通的
子类一样工作,没有特殊的魔法为
区分它们或
重新加载正确的类型与find。

If you don‘t have a type column defined in your table, single-table inheritance won‘t be triggered. In that case, it‘ll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

一个很好的教程在这里: http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/

A pretty good tutorial is here: http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/

这篇关于如何在Ruby on Rails中实现Active Record继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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