Rails 4 many to many association not working

后端 未结 2 583
遇见更好的自我
遇见更好的自我 2021-01-06 10:17

Ruby on rails newbie here. Trying to create a starter blog app and having trouble with many to many association between my models.

I have 2 models - Post, Category t

相关标签:
2条回答
  • 2021-01-06 10:51

    When using the has_and_belongs_to_many association you need a unique index on your join table. Your migration should look like this:

    class CreateCategoriesPosts < ActiveRecord::Migration
      def change
        create_table :categories_posts do |t|
          t.integer :category_id
          t.integer :post_id
          t.timestamps
        end
        add_index :categories_posts, [:category_id, :post_id]
      end
    end
    

    You can also get rid of the CategoriesPost model, that is only needed if you wanted to implement a :has_many, :through association. That should answer your question.


    And just to be thorough, if you wanted to use a :has_many, :through association with a CategoriesPost model you can implement that like so:

    class Post < ActiveRecord::Base
      has_many :categoriesposts
      has_many :categories, :through => :categoriesposts
    end
    class Category < ActiveRecord::Base
      has_many :categoriesposts
      has_many :posts, :through => :categoriesposts
    end
    class CategoriesPost < ActiveRecord::Base
      belongs_to :post
      belongs_to :category
    end
    

    Implementing this method allows you to add more attributes to your categoriespost model if you wanted.

    0 讨论(0)
  • 2021-01-06 10:59

    Further to the first answer, you need to put associations in your join model (CategoriesPosts) like this:

    Class CategoriesPosts  < ActiveRecord::Base
        belongs_to :category
        belongs_to :post
    End
    
    0 讨论(0)
提交回复
热议问题