迁移期间的基本Rails问题(Rails 2.3.11)

时间:2013-02-07 16:01:43

标签: ruby-on-rails migration

我在迁移期间遇到基本的rails问题。这是两个脚本

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

文件#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
***********************************************

这是我在迁移过程中看到的内容 == CreateGoogleMaps:迁移============================================= == - create_table(:google_maps)     - &GT; 0.0638s == CreateGoogleMaps:已迁移(0.0640s)======================================

== CreateMarkers:迁移========================================== ======== - create_table(:markers)     - &GT; 0.0537s == CreateMarkers:已迁移(0.0539s)=========================================

== AddMapStyle:迁移========================================== ========== - add_column(:google_maps,:style,:integer)     - &GT; 0.0406s 耙子流产了! 发生错误,所有后续迁移都已取消:

未初始化的常量AddMapStyle :: GoogleMaps

我正在使用Rails 2.3.11。非常感谢任何调试提示!

2 个答案:

答案 0 :(得分:1)

您不应该在迁移中使用模型,因为它很危险 - 模型可能会发生变化,您正在尝试加载ActiveRecord对象,同时从其下面更改模式。

如果可以,您应该使用SQL,例如以下运行原始更新命令的示例。

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

答案 1 :(得分:1)

您可以安全地在迁移中使用模型,如下所示:

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

由于类是在迁移类中定义的,因此它位于单独的命名空间中。

相关问题