Home > Mobile >  Difference between t.change and change_column in rails?
Difference between t.change and change_column in rails?

Time:08-01

I am new in learning ruby on rails, I am confused when to use change_column and when to use t.change for migrations?

For example

class CreateProducts < ActiveRecord::Migration[7.0]
   def change
     create_table :products do |t|
      t.string :name
      t.text :description
      t.timestamps
     end
   end
 end

CodePudding user response:

The def change method is part of all migrations. This method contains the changes that you want to apply during a given migration.

All your migrations will either have change method or an up and down method. If you define a change method like this:

class CreateProducts < ActiveRecord::Migration[7.0]
   def change
     create_table :products do |t|
      t.string :name
      t.text :description
      t.timestamps
     end
   end
 end

then when you apply this migration, a table will be created, and when you roll back this migration, Rails will try to generate a reverse of the migration. In this case, the reverse of create_table would be to drop the table.

Now suppose you already have this table created, but then you realize that you want to limit the length of the name field, then you can generate a migration to do that. This migration will use change_column method because you are now trying to change the definition of an existing column.

class LimitProductName < ActiveRecord::Migration[7.0]
   def change
     change_column :products, :name, :string, limit: 100
   end
 end
  • Related