Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Migration Change vs Up & Down methods

I am working through the book Rails Test Prescriptions and during the setup it is asking me to change a migration file to the following:

class ProjectUserJoin < ActiveRecord::Migration
  def self.up
    create_table :projects_users, :force => true, :id => false do |t|
      t.references :project
      t.references :user
      t.timestamps
    end
  end

  def self.down
    drop_table :projects_users
  end
end

It seems I am using a later version on Rails (4.0.0) than the book (2 or 3.x) and my migration file looks like this:

class ProjectUserJoin < ActiveRecord::Migration
  def change
  end
end

How do I edit the change method to do the same as the up and down methods above? So far I have tried using up and down as opposed to self.up and self.down and copying in the same code. It did not work.

Thanks!

like image 772
user2623706 Avatar asked Jan 02 '14 19:01

user2623706


People also ask

What is up and down methods in migration?

The up method should describe the transformation you'd like to make to your schema, and the down method of your migration should revert the transformations done by the up method. In other words, the database schema should be unchanged if you do an up followed by a down.

How does rails know which migrations to run?

It will run these migrations in order based on the date of the migration. Note that running the db:migrate also invokes the db:schema:dump task, which will update your db/schema. rb file to match the structure of your database.

How do I downgrade migration in rails?

To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.


2 Answers

Just change def change with def self.up content.

You can check the result by running rake db:migrate at your console - it will create the table (self.up functionality) and rake db:rollback - it will drop the table (self.down functionality).

like image 88
alex Avatar answered Sep 28 '22 02:09

alex


Your up/down migration would look like this for change:

class ProjectUserJoin < ActiveRecord::Migration
  def change
    create_table :projects_users, :force => true, :id => false do |t|
      t.references :project
      t.references :user
      t.timestamps
    end
  end
end

The change method is able to automatically figure out the down actions required based upon the create/update information you provide. It is not a complete replacement for the original self.up/self.down methods however as some database actions you take Rails is not able to automatically figure out what is the corresponding up/down actions. On example of this is if you need to run an arbitrary SQL statement execute-<<SQL ... SQL.

like image 25
CDub Avatar answered Sep 28 '22 01:09

CDub