Rails ActiveRecord::Migration what is the difference between index: true and add_index?

一世执手 提交于 2019-12-03 15:04:21

问题


What is the difference between

t.boolean :is_live, index: true

and

add_index :table_name, :is_live

If there is no difference, how come only the add_index is reflected in schema.rb. When I use index: true, I can't actually see the index in schema.rb. Should I only use the add_index method.

When use the add_index method, I can see this in my schema.rb

add_index "table_name", ["is_live"], name: "index_table_name_on_is_live", using: :blahblah

回答1:


In short: both do the same job. ìndex: true` just saves you an additional line. Look here https://github.com/rails/rails/pull/5262#issuecomment-4329571




回答2:


Just found out that the :index option is for references only (t.references or t.belongs_to). For 'ordinary' column types this option is ignored (that's why indices are not reflected in your schema.db when you used the :index option).

For less verbose syntax there is an index type:

t.index :column_name # extra options may be provided also


来源:https://stackoverflow.com/questions/19914167/rails-activerecordmigration-what-is-the-difference-between-index-true-and-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!