Flip
Flip

Reputation: 6761

How to generate migration to change database column in Rails

I wonder if there is a way to generate migrations that change something in the same fashion as there is for creating tables, adding or removing columns.

E.g. for creating a table I would use:

rails generate migration CreateProducts name:string part_number:string

For adding a column I would use:

rails generate migration AddUserRefToProducts user:references

I took this examples from the Rails Guides but I couldn't find anything for changing a column, let's say to set a default.

Upvotes: 4

Views: 2270

Answers (1)

G. I. Joe
G. I. Joe

Reputation: 1653

From Rails Migrations:

  • change_column(table_name, column_name, type, options): Changes the column to a different type using the same parameters as add_column.

Example, inside your migration:

class ChangeColumnInTablename < ActiveRecord::Migration
  def change
    change_column :tablename, :field, :string , default: <default_value>
  end
end

Upvotes: 3

Related Questions