Rails 4 many to many association not working

梦想的初衷 提交于 2019-12-01 06:51:40

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.

Richard Peck

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!