26

I am new to Model in rails. I know how to create model & how to add column to them. Now I want to set default value to a column but I am not getting that how exactly I can do it.

I generated new model

rails g model User

then added column to it

rails generate migration AddNotificationEmailToUsers notification_email:boolean

Now I want to set value of Notification column default as true. Please guide me how to write the migration for the same. Thank you!!!

mandar.gokhale
  • 1,876
  • 1
  • 18
  • 37

4 Answers4

54

You can't do this from the command line - you'll have to edit the migration file and change the corresponding line to something like

add_column :users, :notification_email, :boolean, :default => true
Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
14

Best approach here is to use change_column in your migration. It is advertised to change type but you can use it to attach a default to existing column.

I had

location   :integer

in schema and I wanted to default to zero, so I wrote a migration as such:

change_column :player_states, :location, :integer, :default => 0

That did the trick.

rkgordon3
  • 141
  • 1
  • 4
2

As of now there is no way around to specify default value defined through terminal in rails migration.

you can execute below steps in order to specify default value for a column

1). Execute

$ rails generate migration AddNotificationEmailToUsers notification_email:boolean

2). Specify the new column default value to TRUE/FALSE by editing the new migration file created.

class AddNotificationEmailToUsers < ActiveRecord::Migration
  def change
    add_column :users, :notification_email, :boolean, default: true
  end
end

3).Run above generated migration by Executing.

$ rake db:migrate
Subhash Chandra
  • 3,165
  • 1
  • 27
  • 30
  • if you want to zero down deployement this will not suitable solution. check this: https://github.com/LendingHome/zero_downtime_migrations#adding-a-column-with-a-default – Ümit Öztürk Jul 12 '21 at 06:36
2

Frederick Cheung is correct you will need to edit the migration file for this. Just a minor update add comma after the data type before specifying the default value.

add_column :users, :notification_email, :boolean, :default => true
Pritesh Jain
  • 9,106
  • 4
  • 37
  • 51
  • Hey guys it is not working for me is there any migration like rails g migration AddDefaultsToTablename :Tablename, :ColumnName :Default value ? – mandar.gokhale Dec 26 '11 at 20:06
  • No, there is no direct way for this, This should work in the migration file that gets generated, what error are u getting? – Pritesh Jain Dec 29 '11 at 09:16