首页 > 解决方案 > Rails 6 子类不会自动创建自己的类型

问题描述

按照教程(https://devblast.com/b/single-table-inheritance-with-rails-4-part-1/),我创建了一个类和子类:

class Animal < ApplicationRecord
  belongs_to :tribe
  self.inheritance_column :race

  scope :lions, -> { where(race: 'Lion') }
  scope :meerkats, -> { where(race: 'Meerkat') }
  scope :wildboars, -> { where(race: 'Wildboar') }

  def self.races
    %w(Lion Wildboar Meerkat)
  end
end

和子类:

lion.rb
class Lion < Animal;end
meerkat.rb
class Meerkat < Animal; end
wildboar.rb
class Wildboar < Animal;end

还有一个与动物相关的课程:

类部落 < ApplicationRecord
  has_many :动物
  # 将 :lions、:meerkats、:wild_boars 委托给: :animals
  代表:狮子,:猫鼬,:野猪,到::动物

结尾

似乎比赛在 tuto 中实现,但是当我创建 Lion 的实例时,实例比赛为 nil :

Lion.new
=> #<Lion id: nil, name: nil, age: nil, race: nil, created_at: nil, updated_at: nil, tribe_id: nil>

在现有 Tribe 中创建时相同:

tribe.animals << Lion.new(name:'toto',age:25)
   (0.2ms)  BEGIN
  Lion Create (1.8ms)  INSERT INTO "animals" ("name", "age", "created_at", "updated_at", "tribe_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["name", "toto"], ["age", 25], ["created_at", "2020-06-28 02:03:56.598482"], ["updated_at", "2020-06-28 02:03:56.598482"], ["tribe_id", 1]]
   (6.9ms)  COMMIT
  Animal Load (0.6ms)  SELECT "animals".* FROM "animals" WHERE "animals"."tribe_id" = $1 LIMIT $2  [["tribe_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Animal id: 7, name: nil, age: nil, race: nil, created_at: "2020-06-27 23:59:30", updated_at: "2020-06-27 23:59:30", tribe_id: 1>, #<Animal id: 9, name: nil, age: nil, race: nil, created_at: "2020-06-28 00:16:43", updated_at: "2020-06-28 00:16:43", tribe_id: 1>, #<Animal id: 10, name: "toto", age: 25, race: nil, created_at: "2020-06-28 02:03:56", updated_at: "2020-06-28 02:03:56", tribe_id: 1>]>

这样做缺少什么?

标签: activerecordruby-on-rails-6single-table-inheritance

解决方案


正如塞巴斯蒂安·帕尔马(Sebastian Palma)在通讯中提到的那样,对此的修复是语法错误:

self.inheritance_column = :race

=失踪了


推荐阅读