Question

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!

Was it helpful?

Solution

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).

OTHER TIPS

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.

It's simpler to work with change, the migration should look like

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

Up and down method is still valid to use but they call it

old style of migration

. You might want to learn more about active record migration from Rails Guide

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top