如何实现在Ruby on Rails的活动记录继承? [英] How to implement Active Record inheritance in Ruby on Rails?

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

问题描述

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

How to implement inheritance with active records?

例如,我要一个类动物,狗类和类目录。

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

如何将模型和数据库表的映射是什么?

How would the model and the database table mapping be?

推荐答案

Rails的支持单表继承。

Rails supports Single Table Inheritance.

AR文档

活动记录允许继承由   存储在类的名   在默认情况下被命名为类型列   (可以通过覆盖来改变   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(:名称=>   37signals公司),这个纪录将是   保存在公司表型   =事务所。第一,名称:然后,您可以再次使用Company.find(读取该行   ='37signals的),它会返回一个企业对象。

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.

如果你没有一个类型列   在表中定义,单表   继承不会被触发。在   这种情况下,它会工作就像正常的   子类没有特别的魔法   他们或区分   重新加载正确的类型与发现。

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.

一个pretty的很好的教程是在这里:<一href="http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/">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的活动记录继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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