Asnad Atta
Asnad Atta

Reputation: 4003

Join table error on running migration

I have two models in rails 5.1

class Category < ActiveRecord::Base
  has_and_belongs_to_many :sub_categories, join_table: "categories_join_table"
end

class SubCategory < ActiveRecord::Base
  has_and_belongs_to_many :categories, join_table: "categories_join_table"
end

I have added multiple migrations the problem is when I try to run migration I get the error ERROR: relation "comfort_factor_sub_categories" does not exist because in the migration to create table comfort_factor_sub_categories will run in later migrations. How can I handle this? Note: I can't change the name of join_table as it is just an example I have long names.

Upvotes: 1

Views: 104

Answers (2)

Lennart L
Lennart L

Reputation: 130

This question is over three years old at the time of this writing, but I just ran into the same problem so I thought I'd share my solution here.

In my case, I was running Rails 6.1, so my error message looked a bit different:

StandardError: An error has occurred, this and all later migrations canceled:

Could not find table 'officers_users'

The officers_users table is a join table that is created in a later migration, but the migration in question doesn't make any use of it, so why was I getting this error?

At first, I thought it might be a Rails bug as my migration was using update_columns to modify the users table, which shouldn't run any callbacks, but then I noticed that the values that I was updating them with were dependent on a computed attribute, which in turn was dependent on the officers_users join table. So Rails was right and I was wrong (once again, hah)! The solution was simply to make the failing migration self-sufficient without needing that computed attribute. Once I did that, everything was good again.

So if you run into the same problem, I would suggest checking your migration with a fine toothed comb and look for any hidden dependencies that might be using the later migration's join table.

Upvotes: 2

mabe02
mabe02

Reputation: 2734

If I understood your problem correctly, you have added several migrations and you cannot run them because some relationship is not found.

In that case, you should duplicate the classes in migrations:

class CreateCategories < ActiveRecord::Migration[5.1]
  class Category < ActiveRecord::Base
    # without declaring the relationship with the table which does not exist yet
  end

  def up
    create_table :categories do |t|
      # t.something
    end
  end
  def down
    drop_table :categories
  end
end

You should then do the same thing for SubCategory.

For creating a proper join_table, you can refer to Rails official documentation

Upvotes: 0

Related Questions