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

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

2 Comments

Hey guys it is not working for me is there any migration like rails g migration AddDefaultsToTablename :Tablename, :ColumnName :Default value ?
No, there is no direct way for this, This should work in the migration file that gets generated, what error are u getting?
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

1 Comment

if you want to zero down deployement this will not suitable solution. check this: github.com/LendingHome/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.