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