camillavk
camillavk

Reputation: 521

add default value to column after migration not working

I created a column in a table as normal and did rake db:migrate. I then realised that I needed to set a default value for the column. After looking on stackoverflow I found several people that said all I had to do was edit the migration file so that this

def change
  add_column :accounts, :equipment_visible, :boolean
end

turns into this

def change
  add_column :accounts, :equipment_visible, :boolean, default: true
end

I did this then ran rake db:migrate again but nothing happened.

I kept looking on for answers as I assume it didn't work because I had already run rake db:migrate.

I then ran another migration and put this into the file;

def change
    def up
      change_column :accounts, :equipment_visible, :boolean, default: true
    end

    def down
      change_column :accounts, :equipment_visible, :boolean, default: nil
    end
  end

but still nothing has happened....does anyone know how I can go about this now?

Many thanks

*EDIT

The schema for the table is like this:

create_table "accounts", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "crafts_visible",    default: true
    t.boolean  "equipment_visible"
  end

I am trying to get the "equipment_visible" to have default: true after it like the "crafts_visible"

Upvotes: 0

Views: 922

Answers (2)

rdalin
rdalin

Reputation: 1

I think you want:

change_column_default :accounts, :equipment_visible, true

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

You have to rollback your migration and migrate db again:

bundle exec rake db:rollback
bundle exec rake db:migrate

or just run redo task:

bundle exec rake db:migrate:redo

Upvotes: 1

Related Questions