I have a model named Post
and a model named Category
. Relationship between Post
and Category
is many-to-many. So I create a join table as following:
create_table :categories_posts do |t|
t.integer :post_id, index: true
t.integer :category_id, index: true
t.timestamps
end
Here is my model Post
(file name: post.rb
)
class Post < ApplicationRecord
has_many :categories, :through => :categories_posts
has_many :categories_posts
end
Here is my model CategoryPost
(file name: category_post.rb
)
class CategoryPost < ApplicationRecord
self.table_name = "categories_posts"
belongs_to :post
belongs_to :category
end
But when I try: Post.last.categories
or Post.last.categories_posts
I meet exception:
NameError: uninitialized constant Post::CategoriesPost
Please tell me where I am wrong.
Thanks
NameError: uninitialized constant Post::CategoriesPost
The plural form of CategoryPost
is CategoryPosts
, so you should use category_posts
instead of categories_posts
when defining associations
class Post < ApplicationRecord
has_many :category_posts
has_many :categories, :through => :category_posts
end
However, if you want to use categories_posts
, you can do with by defining class_name
on the association
class Post < ApplicationRecord
has_many :categories_posts, class_name: "CategoryPost"
has_many :categories, :through => :categories_posts
end