0

我有一个用户表和一个我新创建的老师。老师是用户的子类,所以,我使用脚手架生成器生成老师表,然后,我修改模型做老师是用户的子类。毕竟,我做了一个 db:migrate。然后,我去

http://localhost:3000/teachers/new

它显示一个错误:

undefined method `teacherSalary' for #<Teacher:0x103331900>

所以,我的问题是我做错了什么?我想创建一个用于用户注册的页面,用户只能是老师/学生。但是我不能添加教师记录……而且,我去

http://localhost:3000/users/new

我想要一个组合框,允许用户将他们的用户注册为“老师”或“学生”。但一切似乎都不像我预期的那样工作。我需要做什么?非常感谢您的帮助。

4

3 回答 3

2

I found this definition really handy: STI means one table contains the data of more than one model, usually differentiated by the "type" column. ("users" table contains data for the models "Teacher", ""Pupil", "Employee", "Assistant", etc.) Keeps similar models in the same table instead of creating new ones.

A Polymorphic Association means that one model can be associated with more than one other model(Comment can belong to post, image, file, user_type...) To prevent foreign key conflicts, the association is reperesented with the *_id and *_type columns instead of only *_id.

于 2010-12-21T15:39:14.920 回答
2

在您的数据库中,您应该有一个名为 users 的表。该表应该有一个字符串列,默认情况下称为类型。如果您为此列使用其他名称,则必须使用手动设置继承列名称self.inheritance_column = "column_name"

在您的应用程序中,您有三个模型,用户、学生和教师。User 像往常一样从 ActiveRecord::Base 继承,Student 和 Teacher 都从 User 继承。

然后,您应该能够实例化新的 Teacher 和 Student 对象。在内部,这是通过将模型名称写入用户表上的类型字段,然后在使用Student.find它时向 SQL 添加一个子句以仅返回 type = 'Student' 的行

您可以将共享行为添加到用户类,例如验证等,然后将其他行为添加到继承的类。

可以在Martin Fowlers Book(Patterns of Enterprise Application Architecture)中找到有关 STI 如何工作的更完整描述。

于 2010-07-10T09:04:29.770 回答
0

对于您在这里的情况,我不确定 STI 是否是最好的方法。当存在类似 OO 的继承并且模型具有相同的属性但行为不同时,通常应使用 STI。在您的情况下,教师和学生肯定有一些共享属性,但它们也必然有不同的属性。
您可能还想试验多态关联。

于 2010-07-10T11:56:23.140 回答