如何实现在Ruby on Rails的活动记录继承?

编程入门 行业动态 更新时间:2024-10-24 06:24:55
本文介绍了如何实现在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的很好的教程是在这里:juixe/techknow/index.php/2006/06/03/rails-single-table-inheritance/

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

更多推荐

如何实现在Ruby on Rails的活动记录继承?

本文发布于:2023-10-27 16:02:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何实现   Ruby   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!