Ruby on rails Rails-向InHirting类添加新字段
我有学生模型,继承用户模型 班级学生<用户 如果我给学生添加新字段,它不会显示。我看到的只是Student表中用户字段的副本 rails g型号用户电子邮件:字符串名称:字符串性别:布尔值Ruby on rails Rails-向InHirting类添加新字段,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,ruby-on-rails-3.2,ruby-on-rails-3.1,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,Ruby On Rails 3.2,Ruby On Rails 3.1,我有学生模型,继承用户模型 班级学生
rails g模型学生年龄:整数 rake数据库:迁移 用户模型: 类用户
结束 然后我用 班级学生
如何实现这一点?我认为您对Rails中的
表
和模型
感到困惑
如评论中所述,您有一个设置;您将有一个users
表,可以使用Type
属性将其外推到不同的类(模型):
#app/models/user.rb
class User < ActiveRecord::Base
#columns id | type | other | user | attributes | created_at | updated_at
end
#app/models/student.rb
class Student < User
# uses "users" table
def custom_method
#=> Will only appear with @student.custom_method (IE @user.custom_method will not exist)
end
end
这就是我们在某些应用程序中存储用户的方式:
这使我们能够调用@user.profile.homepage
等,或者如果我们想委派它:
#app/models/user.rb
class User < ActiveRecord::Base
has_one :profile
delegate :homepage, to: :profile, prefix: true #-> @user.profile_homepage
end
#app/models/user.rb
类用户@user.profile_主页
结束
你有一个单表继承,你能给我们看一下实际上添加了你看不到的“字段”的代码吗(例如,显示学生模型的前几行)以及可能更多的用户模型,这样我们就可以看到它是activerecord还是一个普通的ruby类。@Phil-我试着通过迁移再添加一个字段,我仍然没有看到任何字段添加到学生表中,您能告诉我哪里出错了吗?
#app/models/user.rb
class User < ActiveRecord::Base
has_one :profile
delegate :homepage, to: :profile, prefix: true #-> @user.profile_homepage
end