Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding unique: true for add_column and add_index in Active Record

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
like image 235
Richard VanBreemen Avatar asked Jan 31 '13 09:01

Richard VanBreemen


3 Answers

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
like image 147
Alexandru Emil Lupu Avatar answered Oct 10 '22 14:10

Alexandru Emil Lupu


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.

like image 22
Jiří Pospíšil Avatar answered Oct 10 '22 15:10

Jiří Pospíšil


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.

like image 3
webaholik Avatar answered Oct 10 '22 15:10

webaholik