1

I want to add a default value to an existing column in my database, this is my attempt:

add_column :users, :gamelv1, :integer, default: 1

I added default: 1 and run rake db:migrate, but when I check the default value of the gamelv1 column, it is still nil. The value 1 I added is not saved.

How do I set default values for my column?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Marco
  • 141
  • 4
  • 14
  • 3
    If the column already exists, `add_column` shouldn't even succeed. Did the migration run without errors? http://stackoverflow.com/questions/7098602/add-a-default-value-to-a-column-through-a-migration might be helpful, too. – Robert Nubel May 24 '16 at 20:54
  • You should first remove the column and then do this. This will work if you drop and create the database, and then run the migration, but you will of couse loose the data. You can also try to create a new object. If it's one, than it's ok. The existing objects need to be updated manually. Run User.all.each do |u| u.update_attributes(gamelv1: 1) – DR_ May 24 '16 at 21:12

1 Answers1

2

The default value is only applied when a record is first created. Existing records would be unaffected by a change to default. You can manually apply this default value in your migration, by doing this:

add_column :users, :gamelv1, :integer, default: 1

User.reset_column_information

User.where(gamelv1: nil).update_all(gamelv1: 1)

This will find all records in which gamelv1 is nil (null in the database), and will update those records so that gamelv1 has the default value of 1. That way, your data is migrated at the same time as the database structure, so that you app behaves as you expect, regardless of when the record was created.

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43