0
我有一个名为Post
的模型和一个名为Category
的模型。 Post
和Category
之间的关系是多对多的。所以,我创建一个连接表如下: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.categories
或Post.last.categories_posts
我遇到异常:
NameError: uninitialized constant Post::CategoriesPost
请告诉我我错在哪里。
感谢
谢谢。有用。我不明白的是:我使用'categories_posts',因为它遵循rails约定。为什么它不起作用?谢谢。 –
连接表我也使用'categories_posts' –
@TrầnKimDự为'has_many:through'定义第三个模型时没有约定。定义关联时,它应该是一个正确的复数形式。你可以通过''CategoryPost'.pluralize'检查控制台。 – Pavan