activerecord - 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>]>
这样做缺少什么?
解决方案
正如塞巴斯蒂安·帕尔马(Sebastian Palma)在通讯中提到的那样,对此的修复是语法错误:
self.inheritance_column = :race
=
失踪了
推荐阅读
- nativescript - 允许/阻止标签的可访问性字体大小调整
- node.js - 如何断开会话中的所有连接?
- r - 如何导入 csv,使其具有反应性并创建绘图
- mongodb - Kotlin:MongoDB 和 @DBRef 反向引用 -> Stackoverflow 异常
- django - 如何覆盖 get_queryset 方法以仅显示 django 中多对多字段中包含的对象?
- ruby-on-rails - 在 Elastic beanstalk 和 Route 53 上添加 www
- json - 如何在ansible中有条件地从注册的json输出中获取值
- scala - 将 scala 2.13 中的自定义集合操作添加到特定类型的任意集合
- java - 我想用 java 代码创建 JSON 模式
- c++ - 组合两个数组以形成每个项目的一对