【问题标题】:Rails STI add additional fields to childsRails STI 向子项添加附加字段
【发布时间】:2018-02-16 21:10:51
【问题描述】:

我有一个来自Devise gem 的父类User

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :first_name, presence: true, length: { maximum: 256 }
  validates :last_name,  presence: true, length: { maximum: 256 }

  def full_name
    first_name + ' ' + last_name
  end
end

我想在我的项目中拥有两种类型的帐户,例如ParticipantMentor。只要我读过,使用单表继承(STI)是一个很好的方法,但是我新添加的字段并没有出现在模型中。


我有以下迁移文件:

class CreateParticipants < ActiveRecord::Migration[5.1]
  def change
    create_table :participants do |t|
      t.string :team_name
      t.references :mentor

      t.timestamps
    end
  end
end

class CreateMentors < ActiveRecord::Migration[5.1]
  def change
    create_table :mentors do |t|

      t.timestamps
    end
  end
end

简单地说,我想要一个Participant 模型,其中我有额外的team_name 字段以及一个与Mentor 模型的外键关系

participant.rb:

class Participant < User
  # _________________^
  validates :team_name, presence: true, length: { maximum: 500 }

  belongs_to :mentor
end

mentor.rb:

class Mentor < User
  # ____________^
  has_many :participants
end

但是新添加的字段没有出现,虽然出现在db/schema.rb中。

【问题讨论】:

    标签: ruby-on-rails ruby database sti


    【解决方案1】:

    在 STI 中,子模型在数据库中没有特定的表。所有孩子共享父表。您可以在子类中定义新的方法和属性,但如果您想将其保存在数据库中,则必须在父表中创建这些字段。如果您需要很多字段,这不是一个好选择,因为其中很多可能是空的(如果用户不是参与者)

    如果您需要保存更多关于孩子的信息,您可以使用其他方法,例如多态关联:http://guides.rubyonrails.org/association_basics.html(第 2.9 章)

    【讨论】:

      猜你喜欢
      • 2020-11-26
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      相关资源
      最近更新 更多