-1

Based off http://guides.rubyonrails.org/v3.2.21/migrations.html and given the following migration:

class CreateVacations < ActiveRecord::Migration
  def change
    create_table :vacations do |t|
      t.string :name
      t.string :slug, :uniqueness => true
      t.datetime :starts_at
      t.datetime :ends_at
      t.timestamps
    end
  end
end

I ran rake db:migrate and see this schema:

ActiveRecord::Schema.define(:version => 20150825170615) do

  create_table "vacations", :force => true do |t|
    t.string   "name"
    t.string   "slug"
    t.datetime "starts_at"
    t.datetime "ends_at"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

end

I do not ssee any uniqueness requirement for 'slug'. If I did it wrong, how can I fix it at this point?

If it was right, why doesn't the schema say it's unique? Thank you

Arvind
  • 2,671
  • 1
  • 18
  • 32
codyc4321
  • 9,014
  • 22
  • 92
  • 165

1 Answers1

3

You need to create an index in order to enforce uniqueness at the database level:

add_index :vacations, :slug, unique: true
alf
  • 18,372
  • 10
  • 61
  • 92
  • 1
    if I change that old migration and run db:migrate, will it break? – codyc4321 Aug 25 '15 at 17:38
  • 1
    and where do I put that index? in the migration file? – codyc4321 Aug 25 '15 at 17:38
  • 1
    If you haven't checked in the migration to your code repository, you can just run `rake db:rollback`, edit the migration (adding that line) and then `rake db:migrate` again. Otherwise, just create another migration for the index – alf Aug 25 '15 at 17:40