Duncan Yun
Duncan Yun

Reputation: 13

Basic Rails issue during migration (Rails 2.3.11)

I am having basic rails issue during migrations. Here are the two scripts

class CreateGoogleMaps < ActiveRecord::Migration
  def self.up
    create_table :google_maps do |t|
      t.string :name, :null => false
      t.string :description
      t.column "center", :point, :null => false, :srid => 4326, :with_z => false # 4326: WSG84
      t.integer :zoom
      t.datetime :created_at
      t.datetime :updated_at
      t.integer :created_by_id
      t.integer :updated_by_id
    end
  end

  def self.down
    drop_table :google_maps
  end
end

File #2 +++ 003_add_map_style.rb ++++++

class AddMapStyle < ActiveRecord::Migration
  def self.up
      add_column :google_maps, :style, :integer
      GoogleMaps.update_all( "style = 1")
  end

  def self.down
      remove_column :google_maps, :style
  end
end
***********************************************

Here's what I'm seeing during migration == CreateGoogleMaps: migrating =============================================== -- create_table(:google_maps) -> 0.0638s == CreateGoogleMaps: migrated (0.0640s) ======================================

== CreateMarkers: migrating ================================================== -- create_table(:markers) -> 0.0537s == CreateMarkers: migrated (0.0539s) =========================================

== AddMapStyle: migrating ==================================================== -- add_column(:google_maps, :style, :integer) -> 0.0406s rake aborted! An error has occurred, all later migrations canceled:

uninitialized constant AddMapStyle::GoogleMaps

I'm using Rails 2.3.11. Any debugging tip is greatly appreciated !

Upvotes: 1

Views: 76

Answers (2)

catsby
catsby

Reputation: 11342

You can safely use Models in migrations like so:

class AddMapStyle < ActiveRecord::Migration
  class GoogleMaps < ActiveRecord::Base; end

  def self.up
      add_column :google_maps, :style, :integer
      GoogleMaps.update_all( "style = 1")
  end

  def self.down
      remove_column :google_maps, :style
  end
end

Since the class is defined inside the migration class, it is in a separate namespace.

Upvotes: 1

Winfield
Winfield

Reputation: 19145

You should NOT use models in migrations, as it's dangerous - the models may change, you're trying to load ActiveRecord objects while changing the schema out from under them.

You should use SQL if you can, like the following example that runs a raw update command.

class AddMapStyle < ActiveRecord::Migration
  def self.up
      add_column :google_maps, :style, :integer
      execute("UPDATE google_maps SET style=1")
  end

  def self.down
      remove_column :google_maps, :style
  end
end

Upvotes: 1

Related Questions