2017-07-22 60 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