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
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.
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