2017-10-13 66 views
0

我有兩個模型在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的名稱,因爲它只是我長名的示例。

+0

你有沒有做什麼,從什麼在引導有關,建議有什麼不同? http://guides.rubyonrails.org/association_basics.html#creating-join-tables-for-has-and-belongs-to-many-associations能讓你分享你在遷移中所做的一切嗎? – mabe02

回答

0

如果我正確理解你的問題,你已經添加了幾個遷移,你不能運行它們,因爲找不到一些關係。

在這種情況下,你應該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