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!!!
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
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.
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
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