1

it is my first time using Ruby subclass inheritence. I have a parent class A with an attribute "name:string", and a child class B < A with an attribute "bankname:string".

When I use rails console to create a B instance (B.new) I get an object with "name:string" only, and without the "bankname:string" attribute.

My Schema looks like this:

 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

My models are:

class A < ApplicationRecord
end

class B < A
end

Console:

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

1 Answers1

3

In Ruby you an really only inherit from another class if you're using Single Table Inheritance, that is two types that share a common table and the table has a string type column.

Since you're declaring B to be a subclass of A, ActiveRecord takes that to mean the b table is irrelevant, that B uses the A table.

What you need is:

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

Where now you can accommodate STI. Note that all columns are visible to all models, but you can make "bankname" optional for A, or just ignore it, leave it unused.

tadman
  • 208,517
  • 23
  • 234
  • 262