How do I create and use a junction table in Rails?
- by Thierry Lam
I have the following data:
A post called Hello has categories greet
Another post called Hola has categories greet, international
My schema is:
create_table "posts", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "categories", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "posts_categories", :force => true do |t|
t.integer "post_id"
t.integer "category_id"
t.datetime "created_at"
t.datetime "updated_at"
end
After reading the Rails guide, the most suitable relationship for the above seems to be:
class Post < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
end
My junction table also seems to have a primary key. I think I need to get rid of it.
What's the initial migration command to generate a junction table in Rails?
What's the best course of action, should I drop posts_categories and re-create it or just drop the primary key column?
Does the junction table have a corresponding model? I have used scaffold to generate the junction table code, should I get rid of the extra code?
Assuming all the above has been fixed and is working properly, how do I query all posts and display them along with their named categories in the view. For example:
Post #1 - hello, categories: greet
Post #2 - hola, categories: greet, international