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

查看:32
本文介绍了如何在 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.

模型和数据库表的映射是怎样的?

How would the model and the database table mapping be?

推荐答案

Rails 支持单表继承.

Rails supports Single Table Inheritance.

来自 AR 文档:

Active Record 允许继承将类的名称存储在一个默认情况下命名为类型"的列(可以通过覆盖改变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"),这个记录将是保存在公司表中的类型=公司".然后您可以使用 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天全站免登陆