0

I am a bigginer, I have the following scenario in my rails' back end: I want to implement a parent class:

Equipment:   
ID PK  
Brand  
IP


...

And some child classes

Printer:

ID_EQUIPMENT PK and FK 

...

Computers:

ID_EQUIPMENT PK and FK


...

Phones:

ID_EQUIPMENT PK and FK 
...

Among others

But I have 2 problems, the first is how to set the primary key of the parent class to be the primary key of the child classes. The other is how to implement this in controler and routes.

I've been stuck in this for a while

Nirav Patel
  • 1,297
  • 1
  • 12
  • 23

1 Answers1

0

Seems like you are trying to use Single Table Inheretance (e.g., all the data is stored in one table, called equipment)?

if so, you may want to look here.

essentially, you define equipment with a type field:

rails g model Equipment brand ip type

This will create an equipment model file (and a db migration file for the fields)

# app/models/equipment.rb
class Equipment < ApplicationRecord
end

Then you can create some additional model files that inherit equipment:

# app/models/printer.rb
class Printer < Equipment
end

When you create a Printer, it will automatically set the type = Printer

> Printer.create(brand: 'HP', ip: '10.0.0.1')
> equip = Equipment.find_by_ip('10.0.0.1')
> equip.type
=> "Printer"

> equip.is_a?(Printer)
=> true

> equip.is_a?(Equipment)
=> true

Implementing it in controllers and routes depends on what you want our application to do. maybe start with getting the STI working, then figure out how you want to interact with these classes.

andrew21
  • 640
  • 5
  • 8
  • Thank you in advance for responding, i am trying to use Multiple Table Ineretance i think – guilherme aroxa May 22 '18 at 18:43
  • I think that I'm trying to use Multiple Table Ineretance because Printer and the others childs have unique attributes. Am I right? – guilherme aroxa May 22 '18 at 18:49
  • Not sure exactly what you are trying to do. Your should not have a table with the same field as the primary key and foreign key. Can you try explaining what real world problem you are trying to solve? – andrew21 May 22 '18 at 23:42