0

I am trying to make it so certain columns cannot be null. I use change_column no problem but some of these columns have an index attached to them signifying that it is unique.

However when I run this migration:

change_column :users, :username, :string, null: false
change_column :users, :email, :string, null: false
change_column :users, :password, :string, null: false
change_column :users, :terms_agreed, :boolean, null: false

It removes the add_index in the schema

schema.rb

- add_index "users", ["username"], :name => "index_users_on_username_code", :unique => true
- add_index "users", ["email"], :name => "index_users_on_email_code", :unique => true
add_index "users", ["confirmation_code"], :name => "index_users_on_confirmation_code", :unique => true

How do I do this without removing the indexes?

P.S. its not actually removing the indexes in the database. Just in the schema.rb file.

Noah Passalacqua
  • 792
  • 2
  • 8
  • 24

2 Answers2

2

The behaviour of how migrations are treated depends on you database implementation. More info here, but in your migration you should explicitly request an index in your change.

class DoSomethingToTable < ActiveRecord::Migration
  def change
    change_column :users, :username, :string, null: false, index: true
  end
end

See the docs for more information.

Community
  • 1
  • 1
RossMc
  • 426
  • 2
  • 6
0

So still unclear as to what happened, but turns out that the indexes got deleted from the database during some database manipulation.

I just put the schema back the way I needed it to be and ran rake db:setup then my migration again and everything worked fine. Very confusing and a lot of unnecessary time spent trying to figure it out.

Noah Passalacqua
  • 792
  • 2
  • 8
  • 24