2017-07-22 3 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.categoriesまたはPost.last.categories_posts私は例外を満たします:

NameError: uninitialized constant Post::CategoriesPost

私が間違っている場所を教えてください。

おかげ

答えて

3

NameError: uninitialized constant Post::CategoriesPost

あなたがcategories_postsを使用したい場合は、あなたが、しかし、代わりにcategories_posts定める団体

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

category_postsを使用する必要がありますのでCategoryPost複数フォームは、CategoryPostsです協会にclass_nameを定義することでできます

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

ありがとうございました。できます。私が理解していないことは: 'categories_posts'はレール規約に従うためです。なぜそれは動作しません?ありがとう。 –

+0

join table私も 'categories_posts'を使用します –

+0

@TrầnKimD' 'has_many:through'の3番目のモデルを定義する際には規約はありません。アソシエーションを定義するときは、正しい複数形でなければなりません。あなたはCategoryPost ".pluralize"でコンソールでチェックすることができます – Pavan

関連する問題