Rails migration: t.references with alternative name?

前端 未结 5 1142
情歌与酒
情歌与酒 2021-01-30 05:48

So I have a create_table like this for Courses at a School:

create_table :courses do |t|
  t.string :name
  t.references :course
  t.timestamps
end
5条回答
  •  感动是毒
    2021-01-30 06:39

    You can do it this way:

    create_table :courses do |t|
      t.string :name
      t.references :transferrable_as
      t.references :same_as
      t.timestamps
    end
    

    or using t.belongs_to as an alias for t.references

    You can't add foreign_key: true to those two references lines. If you want to mark them as foreign keys at the database level you need to have a migration with this:

    add_foreign_key :courses, :courses, column: :transferrable_as_id
    add_foreign_key :courses, :courses, column: :same_as_id
    

    Update

    In Rails 5.1 and above you can add the foreign key in the migration in the create_table block like this:

    create_table :courses do |t|
      t.string :name
      t.references :transferrable_as, foreign_key: { to_table: 'courses' }
      t.references :same_as, foreign_key: { to_table: 'courses' }
      t.timestamps
    end
    

提交回复
热议问题