0

I've been jumping between design patterns, firstly trying polymorphic, now landing on STI. The main goal is to implement a Server > Host > Guest model where a Server has Hosts, Hosts have Guests and each able to have Posts. Although not the main purpose of the question any ideas in the design matter would be helpful as this is my first rails or ruby project.

What I have now is:

class Device
     has_may :children, :class_name => "Device", :foreign_key => "parent_id"
     belongs_to :parent, :class_name => "Device"

     has_many :posts
end

class Server,Host,Guest < Device 
end

STI is used because Server,Host,Guest basically have the same attributes.

I'm having trouble setting up the routes and controllers so I could view a Server's children which would be of type Host or to create a new Server's Host.

JJRhythm
  • 633
  • 3
  • 10
  • 16

1 Answers1

0

First, a good thing would be to add the following things, making everything easier to use for you :

class Device < ActiveRecord::Base
    has_many :children, :class_name => "Device", :foreign_key => "parent_id"
    has_many :servers, -> { where type: "Server" }, :class_name => "Device", :foreign_key => "parent_id"
    has_many :hosts, -> { where type: "Host" }, :class_name => "Device", :foreign_key => "parent_id"
    has_many :guests, -> { where type: "Guest" }, :class_name => "Device", :foreign_key => "parent_id"
    belongs_to :parent, :class_name => "Device"

    has_many :posts
end

With that, you will be able to do server.hosts, etc, which is quite convenient.

Then, you should move each subclass (Server, Host, Guest) to its own file due to Rails loading system. You can try to access the model Server in the console, you will get an undefined error. To fix it, you need to load the model Device, or simply move each subclass in a different file.

Finally, for the routing/controller part, I will advise you to read this post I wrote about common controller for STI resources : http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-2/.

Note that this is the second part, for more details check out the other articles.

T_Dnzt
  • 244
  • 2
  • 8