45

I want to know if I can pass a default value to the rails g migration command. Something like:

 $ rails generate migration add_disabled_to_users disabled:boolean:false #where false is default value for disabled attribute

in order to generate:

class AddDisabledToUsers < ActiveRecord::Migration
  def change
    add_column :users, :disabled, :boolean, default: false
  end
end
Leantraxxx
  • 4,506
  • 3
  • 38
  • 56

4 Answers4

42

You can't: https://guides.rubyonrails.org/active_record_migrations.html#column-modifiers

null and default cannot be specified via command line.

The only solution is to modify the migration after it's generated. It was the case in Rails 3, still the case in Rails 7

Benjamin Bouchet
  • 12,971
  • 2
  • 41
  • 73
35

Rails migration generator does not handle default values, but after generation of migration file you should update migration file with following code

add_column :users, :disabled, :boolean, default: false

you can also see this link - http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Deepti Kakade
  • 3,053
  • 3
  • 19
  • 30
  • 2
    I know that I can modify the migration after. I want to pass default value as a param on terminal. Context: in a custom generator I'm doing: `generate "migration add_demo_to_#{table_name} demo:boolean"` – Leantraxxx Jul 04 '14 at 13:12
7

Default migration generator in Rails does not handle default values, there is no way around as of now to specify default value defined through terminal in rails migration.

you would like to follow below steps in order to achieve what you want

1). Execute

$ rails generate migration add_disabled_to_users disabled:boolean

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

class AddDisabledToUsers < ActiveRecord::Migration
  def change
    add_column :users, :disabled, :boolean, default: false
  end
end

3). Run above generated migration by Executing.

$ rake db:migrate
Subhash Chandra
  • 3,165
  • 1
  • 27
  • 30
0

Rails 3.2 does not seem to support any kind of command line type modifier based on http://guides.rubyonrails.org/v3.2/migrations.html

The documentation for Rails 4.1 refers to type modifiers but the documentation for Rails 3.2 does not mention the word "modifier" in the page.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338