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
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.
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.
To complete answers in case of editing default value :
In your rails console :
rails g migration MigrationName
In the migration :
def change
change_column :tables, :field_name, :field_type, default: value
end
Will look like :
def change
change_column :members, :approved, :boolean, default: true
end