0

I have two models enterprise and deal_event with habtm association. This relation works with create and when I do

Enterprise.last.deal_events

but throws error

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "deal_events_enterprises" does not exist LINE 1: ...CT  "enterprises".* FROM "enterprises" INNER JOIN "deal_even...

when I do

DealEvent.last.enterprises

My models

enterprise.rb

has_and_belongs_to_many :deal_events

deal_event.rb

has_and_belongs_to_many :enterprises

migration

class CreateDealEventsEnterprisesJoinTable < ActiveRecord::Migration[5.1]
  def change
    create_join_table :deal_events, :enterprises do |t|
      t.index :deal_event_id
      t.index :enterprise_id
    end
  end
end
Shilpi Agrawal
  • 67
  • 1
  • 12

1 Answers1

0

You should be naming the join table as deal_event_enterprises (notice no plural deal_event). Your migration looks like this

class CreateDealEventEnterprises < ActiveRecord::Migration[5.1]
  def change
    create_table :deal_event_enterprises do |t|
      t.integer :deal_event_id
      t.integer :enterprise_id
    end
  end
end

Your has_and_belongs_to_manyassociations should work fine if you migrate your join table as deal_event_enterprises with columns deal_event_id and enterprise_id.

However, would recommend defining your many-to-many relations with has_many :through by defining a model class DealEventEnterprise for your join table. This would make your code more verbose and you can add additional logic to your join model when required. Setting up has_many :through looks like this:

class DealEventEnterprise < ApplicationRecord
  belongs_to :deal_event
  belongs_to :enterprise
end

class Enterprise < ApplicationRecord
  has_many :deal_event_enterprises
  has_many :deal_events, through: :deal_event_enterprises
end

class DealEvent < ApplicationRecord
  has_many :deal_event_enterprises
  has_many :enterprises, through: :deal_event_enterprises
end
sa77
  • 3,563
  • 3
  • 24
  • 37