【问题标题】:Basic Rails issue during migration (Rails 2.3.11)迁移期间的基本 Rails 问题 (Rails 2.3.11)
【发布时间】:2013-01-23 05:01:55
【问题描述】:

我在迁移过程中遇到了基本的导轨问题。这是两个脚本

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) -> 0.0638s == CreateGoogleMaps: 迁移 (0.0640s) =====================================

== CreateMarkers:迁移 =========================================== ======== -- create_table(:markers) -> 0.0537 秒 == CreateMarkers:迁移(0.0539s)========================================

== AddMapStyle:迁移 =========================================== ========== -- add_column(:google_maps, :style, :integer) -> 0.0406s 耙中止! 发生错误,所有后续迁移均已取消:

未初始化的常量 AddMapStyle::GoogleMaps

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

【问题讨论】:

    标签: ruby-on-rails migration


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      您可以像这样在迁移中安全地使用模型:

      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
      

      由于类是在迁移类内部定义的,所以它位于单独的命名空间中。

      【讨论】:

      • 如果您在迁移运行期间执行的任何迁移中修改 google_maps 表,这可能会导致架构同步错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      • 2015-08-30
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多