0

My join table wasn't working correctly so I tried to fix it by changing the syntax in the migrations.

I have a building, organization, and OrganizationBuilding classes

The original was

class CreateOrganizationBuildings < ActiveRecord::Migration
  def change
    create_table :organization_buildings, id: :uuid do |t|
      t.uuid :organization_id, index: true
      t.uuid :building_id, index: true
      t.boolean :active, default: true
      t.timestamps
    end
  end
end

I tried to change it to

class CreateOrganizationBuildings < ActiveRecord::Migration
  def change
    create_table :organization_buildings, do |t|
      t.belongs_to :organization, index: true
      t.belongs_to :building, index: true
      t.boolean :active, default: true
      t.timestamps
    end
  end
end

I have three different organizations one of the organizations building association worked correctly before and the rest didn't now none of them are working correctly.

class OrganizationBuilding < ActiveRecord::Base
  belongs_to :organization
  belongs_to :building

  validates :organization, presence: true
  validates :building, presence: true
  validates :building, uniqueness: { scope: :organization }
end

class OrganizationBuilding < ActiveRecord::Base
  belongs_to :organization
  belongs_to :building

  validates :organization, presence: true
  validates :building, presence: true
  validates :building, uniqueness: { scope: :organization }
end

class Building < ActiveRecord::Base
  include Cloneable, SoftDestruction

  has_many :apartments
  has_many :organization_buildings
  has_many :organizations, through: :organization_buildings
  has_many :meters, as: :audit_structure
  has_one :audit_structure, as: :physical_structure
end

Is there a problem when a redo a join table migration that it doesn't associate the database correctly?

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
almusavi
  • 1
  • 2
  • 1
    I think you want to use `t.references` instead of `t.belongs_to` – MrYoshiji Nov 01 '17 at 17:57
  • 1
    @MrYoshiji From the [fine manual](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-references): "references ... Also aliased as: belongs_to". They're the same thing. – mu is too short Nov 01 '17 at 18:08
  • (1) What do you mean by "wasn't working correctly"? (2) Are your `id` columns UUIDs or integers? You seem to be dropping the UUID part in your updated migration. (3) Remigrating will lose all your `organization_buildings` data, was that intended? – mu is too short Nov 01 '17 at 18:11
  • No I wanted to keep my organization_buildings data is there any way to bring it back? – almusavi Nov 01 '17 at 18:18
  • I had a loop to go through the organizations, so the first organization.buildings seemed to work but the second organization.buildings didn't work so i was messsing around with the syntax. – almusavi Nov 01 '17 at 18:20

0 Answers0