Why did Rails 5 changed “index” to “foreign key”?

前端 未结 3 729
迷失自我
迷失自我 2021-02-08 06:56

If you had this in Rails 4:

t.references :event, index: true

Now you could use foreign_key instead of index in Rails

3条回答
  •  旧巷少年郎
    2021-02-08 07:18

    In Rails 5 - when we reference a model, index on the foreign_key is automatically created.

    Migration API has changed in Rails 5 -

    Rails 5 has changed migration API because of which even though null: false options is not passed to timestamps when migrations are run then not null is automatically added for timestamps.

    Similarly, we want indexes for referenced columns in almost all cases. So Rails 5 does not need references to have index: true. When migrations are run then index is automatically created.

    As an example - (Copying from http://blog.bigbinary.com/2016/03/01/migrations-are-versioned-in-rails-5.html)

    When you run rails g model Task user:references

    Rails 4 would generate

    class CreateTasks < ActiveRecord::Migration
      def change
        create_table :tasks do |t|
          t.references :user, index: true, foreign_key: true
          t.timestamps null: false
        end
      end
    end
    

    And rails 5 would generate

    class CreateTasks < ActiveRecord::Migration[5.0]
      def change
        create_table :tasks do |t|
          t.references :user, foreign_key: true
          t.timestamps
        end
      end
    end
    

提交回复
热议问题