2017-07-22 63 views
0

我有一個名爲Post的模型和一個名爲Category的模型。 PostCategory之間的關係是多對多的。所以,我創建一個連接表如下:ActiveRecord:定義多對多關係時初始化常量異常

create_table :categories_posts do |t| 
    t.integer :post_id, index: true 
    t.integer :category_id, index: true 

    t.timestamps 
end 

這裏是我的模型Post(文件名:post.rb

class Post < ApplicationRecord 
    has_many :categories, :through => :categories_posts 
    has_many :categories_posts 
end 

這裏是我的模型CategoryPost(文件名:category_post.rb

class CategoryPost < ApplicationRecord 
    self.table_name = "categories_posts" 
    belongs_to :post 
    belongs_to :category 
end 

但是,當我嘗試:Post.last.categoriesPost.last.categories_posts我遇到異常:

NameError: uninitialized constant Post::CategoriesPost

請告訴我我錯在哪裏。

感謝

回答

3

NameError: uninitialized constant Post::CategoriesPost

複數形式的CategoryPostCategoryPosts,所以你應該定義協會

class Post < ApplicationRecord 
    has_many :category_posts 
    has_many :categories, :through => :category_posts 
end 

時,但是使用category_posts,而不是categories_posts,如果你想使用categories_posts,你可以通過定義class_name關聯

class Post < ApplicationRecord 
    has_many :categories_posts, class_name: "CategoryPost" 
    has_many :categories, :through => :categories_posts 
end 
+0

謝謝。有用。我不明白的是:我使用'categories_posts',因爲它遵循rails約定。爲什麼它不起作用?謝謝。 –

+0

連接表我也使用'categories_posts' –

+0

@TrầnKimDự爲'has_many:through'定義第三個模型時沒有約定。定義關聯時,它應該是一個正確的複數形式。你可以通過''CategoryPost'.pluralize'檢查控制檯。 – Pavan