Adding unique: true for add_column and add_index in Active Record

帅比萌擦擦* 提交于 2019-12-08 15:04:43

问题


Even though my application isn't gonna allow a user to key in a location, I wanted to enforce a uniqueness on city in the database. Since my Rails app will be searching on the city column, I would like to add an index on the city column as well but was wondering if it matters adding unique: true on the index as well. Is this repetitive? If this doesn't make sense, I would really appreciate it if you could explain why.

class CreateLocations < ActiveRecord::Migration
  def change
    create_table :locations do |t|
      t.string :city, unique: true
      t.string :state

      t.timestamps
    end

    add_index :locations, :city, unique: true
  end
end

回答1:


As far as I know the unique option in the create_table block is actually not supported and doesn't do anything, see TableDefinition. To create the unique index, you need to call the method add_index the way you do now. Note that a unique index is both for uniqueness and for searching etc., there's no need to add two indexes on the same column.




回答2:


Using Rails 4, you can provide: index param a hash argument

class CreateLocations < ActiveRecord::Migration
  def change
    create_table :locations do |t|
      t.string :city, index: {unique: true}
      t.string :state

      t.timestamps
    end
  end
end



回答3:


You can specify unique index while scaffolding:

rails generate model Locations city:string:uniq state:string

This will create Model, Spec, Factory and this migration:

class CreateLocations < ActiveRecord::Migration
  def change
    create_table :locations do |t|
      t.string :city
      t.string :state

      t.timestamps null: false
    end
    add_index :locations, :city, unique: true
  end
end

Rails knows what it's doing - nothing more is required.



来源:https://stackoverflow.com/questions/14622143/adding-unique-true-for-add-column-and-add-index-in-active-record

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