简体   繁体   English

Rails模型继承

[英]Rails Model Inheritance

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

You would need to create a table with all of the fields, as well as specify a type column. 您需要创建一个包含所有字段的表,并指定一个类型列。 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. 订阅者将继承Users模型中的所有内容。 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. 只会获得订阅者,就好像你没有使用'type'列一样,它也会找到用户。

You want single table inheritance , described at the link by Alex Reisner. 您需要单表继承 ,由Alex Reisner在链接中描述。 STI uses a single table to represent multiple models that inherit from a base model. STI使用单个表来表示从基础模型继承的多个模型。 In the Rails world, the database schema has a column which specifies the type of model represented by the row. 在Rails世界中,数据库模式有一个列,用于指定行所表示的模型类型。 Adding a column named type in 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' ). 在数据库迁移中添加一个名为type的列,Rails推断该表使用了STI,尽管如果在数据模型中指定了名称,该列可以是任意名称(请参阅类方法'inheritance_column' )。 Note that this makes type a reserved word. 请注意,这使得type成为保留字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM