简体   繁体   中英

How to add default value to a column being added through 'rails g migration' command

I know how to add default value in a migration file already created. ie,

`rails generate migration AddTestColumnToTesttable test_status:boolean` to create it.

It will generate this migration:

class AddTestColumnToTable < ActiveRecord::Migration
  def change
    add_column :table, :test_status, :boolean, :default => true
  end
end

But, Can we add the default value through rails g migration command itself?

No , it can't be done from the command line, you need to change it in the migration file

add_column :table, :test_status, :boolean, :default => true

Hope that helps!

**Rails 4.X +**

Still now, as there is no option to add new column to a table with default value defined through terminal in rails migration, The following steps to be followed to add a new column to an existing table with default value true or false.

1. Run the migration from command line to add the new column

$ rails generate migration add_columnname_to_tablename columnname:boolean

The above command will add a new column in your table.

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

class AddColumnnameToTablename < ActiveRecord::Migration
  def change
    add_column :tablename, :columnname, :boolean, default: false
  end
end

**3. To make the changes into your application database table, run the following command in terminal**

$ rake db:migrate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM