How do I create and use a junction table in Rails?

Posted by Thierry Lam on Stack Overflow See other posts from Stack Overflow or by Thierry Lam
Published on 2010-03-21T05:26:52Z Indexed on 2010/03/21 5:31 UTC
Read the original article Hit count: 378

Filed under:
|

I have the following data:

  1. A post called Hello has categories greet
  2. 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.

  1. What's the initial migration command to generate a junction table in Rails?
  2. What's the best course of action, should I drop posts_categories and re-create it or just drop the primary key column?
  3. 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

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about beginner