Rails migration for change column
We have script/generate migration add_fieldname_to_tablename fieldname:datatype
syntax for adding new columns to a model.
On the same line, do we have a script/generate for changing the datatype of a column? Or should I write SQL directly into my vanilla migration?
I want to change a column from datetime
to date
.
I think this should work.
change_column :table_name, :column_name, :date
You can also use a block if you have multiple columns to change within a table.
Example:
change_table :table_name do |t|
t.change :column_name, :column_type, {options}
end
See the API documentation on the Table class for more details.
I'm not aware if you can create a migration from the command line to do all this, but you can create a new migration, then edit the migration to perform this taks.
If tablename is the name of your table, fieldname is the name of your field and you want to change from a datetime to date, you can write a migration to do this.
You can create a new migration with:
rails g migration change_data_type_for_fieldname
Then edit the migration to use change_table:
class ChangeDataTypeForFieldname < ActiveRecord::Migration
def self.up
change_table :tablename do |t|
t.change :fieldname, :date
end
end
def self.down
change_table :tablename do |t|
t.change :fieldname, :datetime
end
end
end
Then run the migration:
rake db:migrate
As I found by the previous answers, three steps are needed to change the type of a column:
Step 1:
Generate a new migration file using this code:
rails g migration sample_name_change_column_type
Step 2:
Go to /db/migrate
folder and edit the migration file you made. There are two different solutions.
def change change_column(:table_name, :column_name, :new_type) end
2.
def up
change_column :table_name, :column_name, :new_type
end
def down
change_column :table_name, :column_name, :old_type
end
Step 3:
Don't forget to do this command:
rake db:migrate
I have tested this solution for Rails 4 and it works well.