Rails的模型继承 [英] Rails Model Inheritance

查看:145
本文介绍了Rails的模型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个用户,我想使不同类型的用户,说只是普通用户,只用电子邮件和谁拥有一个网站领域的用户,我将如何让用户继承一切从用户只有一个附加字段?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆