1

I already saw this but I'm not sure how to apply it my particular situation How do I add migration with multiple references to the same model in one table? Ruby/Rails

I'm trying to find a way to have a model called ChildOrganization reference 2 columns from another model called Organization in a one-to-many relationship in a Rails 4.2 web app.

For example, org1 and org2 are both listed in the Organization model and have columns such as name, address, etc... but in the ChildOrganization model org1_id and org2_id should be listed under 'parent' and 'child' columns to make a parent\child pair. The goal is to have a ChildOrganization model that lists pairs of two's from the Organization model.

the ChildOrganization has a reference column called organization_id that links to the Organization table and another column that just takes an integer called child_organization_id

in the Organization model (the below is wrong)

has_many :child_organizations, class_name: "ChildOrganization", foreign_key: "organization_id", dependent: :destroy
has_many :child_organizations, class_name: "ChildOrganization", foreign_key: "child_organization_id", dependent: :destroy

in the ChildOrganization model

belongs_to :organization

UPDATE

Here's what worked. In the organization model I have the below. The associations can be called anything, they are not the names of models\tables. You specify the model by using class_name

  # child_organization_parents/children associations map to foreign keys in the ChildOrganization table
  has_many :child_organization_parents, class_name: "ChildOrganization", foreign_key: "parent_org_id", dependent: :destroy
  has_many :child_organization_children, class_name: "ChildOrganization", foreign_key: "child_org_id", dependent: :destroy

in the ChildOrganization model

  belongs_to :organization

the migration looks like this, I added a check for null and also an index

create_table :child_organizations do |t|
  t.integer :parent_org_id, null: false, index: true
  t.integer :child_org_id, null: false, index: true

  t.timestamps null: false
end

here's the command I used to create the model that will hold the 2 foreign keys, remember to add the null:false and index:true to the migration file before running it.

rails g model ChildOrganization parent_org_id:integer child_org_id:integer --no-assets --no-test-framework
random_user_0891
  • 1,863
  • 3
  • 15
  • 39

1 Answers1

1

This first argument after the has_many needs to be different.

Something like this:

has_many :child_organization_organizations, class_name: "ChildOrganization", foreign_key: "organization_id", dependent: :destroy
has_many :child_organization_child_organizations, class_name: "ChildOrganization", foreign_key: "child_organization_id", dependent: :destroy
Dan
  • 1,238
  • 2
  • 17
  • 32