Ruby继承-子实例只有父属性

问题描述 投票:-1回答:1

这是我第一次使用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>

ruby-on-rails ruby inheritance subclass
1个回答
0
投票

在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的可选选项,或者忽略它,使其不使用。

© www.soinside.com 2019 - 2024. All rights reserved.