Search code examples
ruby-on-railsrails-migrationsmodel-associations

Do I need a foreign key declaration in the individual table when creating join table?


I have a join table of "contents" and "roles" called content_roles and this is the join table.

class CreateContentRoles < ActiveRecord::Migration
  def change
    create_table :content_roles, :id => false do |t|
      t.belongs_to :content, foreign_key: "content_id"
      t.belongs_to :roles, foreign_key: "role_id"
    end
    add_index :content_roles, ["content_id", "roles_id"]
  end
end

So in the individual roles and contents migration, do I need to have a foreign_key that refers back to the join table and/or the roles/contents? Sorry, I didn't explain this any better.


Solution

  • The id columns in the content and roles tables act as foreign keys. Rails joins the content and content_roles tables using id in content table and content_id in content_roles table. So are the roles and content_roles tables.