Rails migration for has_and_belongs_to_many join table

后端 未结 6 1426
花落未央
花落未央 2020-11-29 15:40

How do I do a script/generate migration to create a join table for a has_and_belongs_to_many relationship?

The application runs on Rails 2.

6条回答
  •  眼角桃花
    2020-11-29 16:35

    I like doing:

    rails g migration CreateJoinedTable model1:references model2:references. That way I get a migration that looks like this:

    class CreateJoinedTable < ActiveRecord::Migration
      def change
        create_table :joined_tables do |t|
          t.references :trip, index: true
          t.references :category, index: true
        end
        add_foreign_key :joined_tables, :trips
        add_foreign_key :joined_tables, :categories
      end
    end
    

    I like having index on these columns because I'll often be doing lookups using these columns.

提交回复
热议问题