Search code examples
ruby-on-railsrubyactiverecordhas-and-belongs-to-many

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.


Solution

  • 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.