加入表错误上运行迁移
问题描述:
我有两个模型在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
我已经加入多次迁移的问题是,当我尝试运行迁移我的错误ERROR: relation "comfort_factor_sub_categories" does not exist
因为在移民创建表comfort_factor_sub_categories将在稍后的迁移中运行。我该如何处理? 注意:我无法更改join_table的名称,因为它只是我长名的示例。
答
如果我正确理解你的问题,你已经添加了几个迁移,你不能运行它们,因为找不到一些关系。
在这种情况下,你应该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
您应该然后做同样的事情SubCategory
。
为了创建一个适当的join_table,你可以参考到Rails official documentation
你有没有做什么,从什么在引导有关,建议有什么不同? http://guides.rubyonrails.org/association_basics.html#creating-join-tables-for-has-and-belongs-to-many-associations能让你分享你在迁移中所做的一切吗? – mabe02