【问题标题】:Rails - adding new field to inherting classRails - 向继承类添加新字段
【发布时间】:2015-12-31 02:13:11
【问题描述】:

我有 Student 模型,继承 User 模型

班级学生

如果我向学生添加新字段,它不会显示。我看到的只是学生表中用户字段的副本。

rails g 模型用户电子邮件:字符串名称:字符串性别:布尔
rails g model 学生年龄:整数

rake db:迁移

用户模型:

类用户 验证 :email、:name、presence: true
结束

然后我将
class Student <:base>

班级学生 结束

现在 :age 字段已替换为 Student 表中的 :email, :name, :gender 字段,我无法再访问 :age 字段了

学生应该有用户字段以及它自己的附加字段。
我该如何做到这一点?

【问题讨论】:

  • 您能否向我们展示实际添加您看不到的“字段”的代码(例如,展示您的学生模型的前几行)以及可能更多的用户模型,所以我们可以看看它是 activerecord 还是只是一个普通的 ruby​​ 类。
  • @Phil - 我尝试通过迁移添加一个字段,但我仍然没有看到任何字段添加到学生表中,你能告诉我哪里出错了吗?

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-3.1


【解决方案1】:

我认为您对 Rails 中的 tablesmodels 感到困惑。

如 cmets 中所述,您有一个 Single Table Inheritance 设置;您将拥有一个 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

这意味着在这种情况下您没有两个表; Student 将使用 User 表。

如果您希望在Student 模型中使用自定义属性,您可以(如上所述)。最终,对于 STI,您必须对所有继承的模型使用同一个表。如果您需要添加额外的属性,则必须附加到“父”表。

--

学生应该有自己的用户字段以及其他字段

如果有很多属性,你必须建立另一个表来存储它们,然后将两个模型关联起来。会比较麻烦,但总比在一个表中存储大量空单元格要好:

#app/models/user.rb
class Student < ActiveRecord::Base
   has_one :profile
end

#app/models/profile.rb
class Profile < ActiveRecord::Base
   belongs_to :student
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多