Rails 模型继承 [英] Rails Model Inheritance
问题描述
如果我有一个 User 并且我想创建不同类型的用户,比如只有一个电子邮件的普通用户和一个有网站字段的订阅者,我如何让订阅者从只添加一个字段的 Users 继承所有内容?
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?
推荐答案
您需要创建一个包含所有字段的表,并指定一个类型列.即
You would need to create a table with all of the fields, as well as specify a type column. i.e
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.
这篇关于Rails 模型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!