I am adding a new migration to my rails app's database, in it I am adding columns to a new application. Some of the columns have defaults. I would like to add defaults to some of the existing columns as well. My code currently looks like this:
class AddStuffToTable < ActiveRecord::Migration
def change
add_column :table, :column4, :string
add_column :table, :column5, :boolean, default: false
add_default_to_column :table, :column1, default: 0
add_default_to_column :table, :column2, default: 5.8
end
end
I know add_default_to_column
is not the correct syntax. What is the correct syntax/method name? Also, for a integer/decimal column, is the above the correct way to add a default number (I mean do I need anything other than the number itself, such as "" for a string etc.)
As per the rails api on ActiveRecord::Migration , you can use the following method:
change_column(table_name, column_name, type, options)
So in your case that would be:
change_column(:table, :column1, :integer, default: 0)
change_column(:table, :column2, :float, default: 5.8)
That should change your first column to an integer with a default value of 0, and your second column to a float with a default value of 5.8.
you may try:
add_column :table, :column5, TrueClass, :default => false
and
change_column :table, :column4, Integer, :null => false, :default => 0
You don't need to specify a number as string. Check the code below for correct syntax.
class AddStuffToTable < ActiveRecord::Migration
def change
add_column :table, :column4, :string
add_column :table, :column5, :boolean, :default => false
add_column :table, :column1, :default => 0
add_column :table, :column2, :default: => 5.8
end
end
Thank you guys. I tried change_column
as you suggested, and apparently there is also a change_column_default
method, therefore the code is:
class AddStuffToTable < ActiveRecord::Migration
def change
add_column :table, :column4, :string
add_column :table, :column5, :boolean, default: false
change_column_default :table, :column1, default: 0
change_column_default :table, :column2, default: 5.8
end
end
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.