user2453676
user2453676

Reputation: 542

How to add associations for polymorphic join table

I have a polymorphic join table that I want to create using the following migration.

    create_table :sourceables do |t|
      t.string :object_type, null: false
      t.bigint :object_id, null: false
      t.string :source_type, null: false
      t.string :source_id, null: false
    end

An instance of a Sourceable model has an object and a source. A source relationship is a lot like a child/parent relationship. For example, a person with id 1 has parents with id 2 and 3.

{object_type: Person, object_id: 1, source_type: Person, source_id: 2}
{object_type: Person, object_id: 1, source_type: Person, source_id: 3}

I don't fully understand the Rails guides on polymorphism. It looks like the database columns are on the object table, rather than on a join table.

What I would like to know is, how to set up the association in the person model and sourceable model, so I can do something like person.sources to get all of a child's parents.

Upvotes: 0

Views: 42

Answers (1)

user2453676
user2453676

Reputation: 542

I changed my table name from sourceables to parent_child_relationships.

    create_table :parent_child_relationships do |t|
      t.string :parent_type, null: false
      t.bigint :parent_id, null: false
      t.string :child_type, null: false
      t.bigint :child_id, null: false
    end

In the model, ApInvoice, I have:

class ApInvoice < ApplicationRecord
  has_many :parent_relationships, class_name: "ParentChildRelationship", as: :parent, foreign_key: :child_id
  has_many :parent_ap_invoices, through: :parent_relationships, source: :parent, source_type: "ApInvoice"
  has_many :child_relationships, class_name: "ParentChildRelationship", as: :child, foreign_key: :parent_id
  has_many :child_ap_invoices, through: :child_relationships, source: :child, source_type: "ApInvoice"
end

Currently, each ap invoice only has one parent. I'm changing it to a many to many relationship.

To test my code, I did:

ap_invoice.parent_ap_invoices.first.child_ap_invoices.first.id

Since this ap invoice only has one parent, and the parent only has one child, the ap invoice's id should match the parent's child's id.

Upvotes: 0

Related Questions