【问题标题】:Ruby inheritance - child instance has only parent attributesRuby 继承 - 子实例只有父属性
【发布时间】:2019-11-10 08:44:52
【问题描述】:

这是我第一次使用 Ruby 子类继承。 我有一个带有属性“名称:字符串”的父类 A, 和一个子类 B

当我使用 rails 控制台创建一个 B 实例 (B.new) 时,我得到一个只有“name:string”且没有“bankname:string”属性的对象。

我的架构如下所示:

 create_table "a", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "b", force: :cascade do |t|
    t.string   "bankname"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
  end

我的模型是:

class A < ApplicationRecord
end

class B < A
end

控制台:

2.4.0 :010 > c = B.new
 => #<B id: nil, name: nil, created_at: nil, updated_at: nil>

【问题讨论】:

  • 为什么是force: :cascade

标签: ruby-on-rails ruby inheritance subclass


【解决方案1】:

在 Ruby 中,如果您使用 Single Table Inheritance,您实际上只能从另一个类继承,即共享一个公共表的两种类型,并且该表有一个字符串 type 列。

由于您将B 声明为A 的子类,ActiveRecord 认为这意味着b 表无关紧要,B 使用A 表。

你需要的是:

create_table "a", force: :cascade do |t|
  t.string "type"
  t.string "name"
  t.string "bankname"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

现在您可以在哪里适应 STI。请注意,所有列对所有模型都是可见的,但您可以将“bankname”设置为 A 的可选,或者直接忽略它,不使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-27
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多