Ruby-on-rails Rails 模型继承

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6429725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:27:04  来源:igfitidea点击:

Rails Model Inheritance

ruby-on-railsactiverecord

提问by DudeGuySomethingTimes

If I have a User and I want to make different types of users, say just normal users with only an email and subscribers who have a website field, how would I make subscribers inherit everything from Users with just an added field?

如果我有一个 User 并且我想创建不同类型的用户,比如说只有一个电子邮件的普通用户和一个有网站字段的订阅者,我如何让订阅者从只添加一个字段的 Users 继承所有内容?

回答by Olives

You would need to create a table with all of the fields, as well as specify a type column. i.e

您需要创建一个包含所有字段的表,并指定一个类型列。IE

create_table :users do |t|
  t.string :email
  t.string :website
  t.string :type
end

Then you can have classes like

然后你可以有这样的课程

Class User < ActiveRecord::Base

Class Subscriber < User

A subscriber will inherit everything from the Users model. The type column is there so that you can distinguish from the different models. For instance using

订阅者将从用户模型中继承所有内容。类型列在那里,以便您可以区分不同的模型。例如使用

Subscriber.all 

Will only get subscribers, where as if you did not use the 'type' column it would also find users too.

只会获得订阅者,就好像您没有使用“类型”列一样,它也会找到用户。

回答by Fred

You want single table inheritance, described at the link by Alex Reisner. STI uses a single table to represent multiple models that inheritfrom a base model. In the Rails world, the database schema has a column which specifies the type of model represented by the row. Adding a column named typein a database migration has Rails infer the table uses STI, although the column can be an arbitrary name if you specify the name in the data model (see the class method 'inheritance_column'). Note that this makes typea reserved word.

您需要单表继承,在 Alex Reisner 的链接中进行了描述。STI 使用单个表来表示从基本模型继承的多个模型。在 Rails 世界中,数据库模式有一个列,用于指定由行表示的模型类型。添加一个type在数据库迁移中命名的列,Rails 会推断该表使用 STI,但如果您在数据模型中指定名称,该列可以是任意名称(请参阅类方法 'inheritance_column')。请注意,这是type一个保留字。