How do I correctly structure & associate a delegated type and its associations within Rails?

370 Views Asked by At

In an effort to not have multiple of the same record/similar records I'm investigating using delegated_type however Im stumped on just how my associations should/would work.

I've a table, Item that uses delegation for class table inheritance for InvoiceItem, OrderItem, NoteItem and BasketItem.

I have parent tables for item, PurchaseOrder, DeliveryNote and Invoice.

  • A PurchaseOrder will have many items, where the itemable is OrderItem OR BasketItem.
  • A DeliveryNote will have many items, where the itemable is NoteItem
  • An Invoice will have many items, where the itemable is InvoiceItem

item.rb

delegated_type :itemable, primary_key: :uuid, types: ["OrderItem", "InvoiceItem", "NoteItem", "BasketItem"]

NoteItem/InvoiceItem/OrderItem/BasketItem

has_one :item, as: :itemable, dependent: :destroy

Now I'm unsure if an Item should belong to a PurchaseOrder or whether the inherited table (OrderItem/BasketItem) should be the relation.

An example:

PurchaseOrder.rb

has_many :order_items, -> { where(itemable_type: OrderItem) }, class_name: "Items",
                                                                            foreign_key: "purchase_order_id",
                                                                            inverse_of: :purchase_order,
                                                                            dependent: :destroy

OrderItem.rb

belongs_to :purchase_order, class_name: "PurchaseOrder"

I believe the first option should be the correct way, but I'm unsure how that belongs_to would work for the sub-items, should an OrderItem belong_to a PurchaseOrder? This would result in a PurchaseOrder having many items where itemable is OrderItem, but only the OrderItem belongs to the PurchaseOrder, but perhaps this is correct and I am misinterpreting the delegated_type documentation.

Thanks.

Documentation:

Versions: Rails 7.0.4, Ruby 3.0.1 and PGSQL 14

0

There are 0 best solutions below