3

In rails 2 I had a lib/migration_helpers.rb file with methods for setting and dropping foreign keys in the db. These methods were available in self.up and self.down in migration files by adding in the migration file

require 'migration_helpers'

at the top, and

extend MigrationHelpers

immediately after the class statement.

In rails 3 this does not work, and if i try to run a migration using set_foreign_key method from migration_helpers.rb the following error is thrown:

==  AddFkToArticles: migrating ================================================
-- set_foreign_key("articles", "book_id", "books")
rake aborted!
An error has occurred, this and all later migrations canceled:

undefined method `set_foreign_key' for #<AddFkToArticles:0x000001034a1f38>

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

I already checked that in config/application.rb the autoload path is set to include lib. The file is effectively required, because if i comment out the require statement then rails whines about the missing 'migration_helpers' file.

I suspect this is a scoping problem (rails 2 used "def self.up", rails 3 uses "def change") but cannot imagine how to solve the problem (by now I simply copied the code in the migration file, just to check that it does what it should do).

Francesco

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
kranz
  • 599
  • 1
  • 6
  • 23

1 Answers1

5

I don't know what exactly you're trying to accomplish but here's some code that might give you a clue.

## lib/test_helper.rb
module TestHelper

  def my_table_name
    return :mytable 
  end

end

And then the migration:

## db/migrate/test_migration.rb
include TestHelper

class TestMigration < ActiveRecord::Migration

  def self.up
    create_table my_table_name
  end

  def self.down
    drop_table my_table_name
  end
end

Including this helper inside the Migration class doesn't work so it should be outside.

Lenart
  • 3,101
  • 1
  • 26
  • 28
  • 2
    I had to add require File.expand_path('../../../lib/test_helper', __FILE__) to the top of my migration file. Without it, it wouldn't work. – baash05 May 17 '12 at 23:59
  • You need to `extend TestHelper` inside the class if you want the mixin to work with your class methods (like up and down). – Asfand Qazi Nov 10 '21 at 09:49