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
PurchaseOrderwill have many items, where theitemableisOrderItemORBasketItem. - A
DeliveryNotewill have many items, where theitemableisNoteItem - An
Invoicewill have many items, where theitemableisInvoiceItem
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