【问题标题】:Model won't save changes when using Model.update_attributes! during Rails 3 migration使用 Model.update_attributes 时模型不会保存更改!在 Rails 3 迁移期间
【发布时间】:2012-07-26 04:07:46
【问题描述】:

我有以下 Rails 3 迁移,它将列 game_type 添加到名为 games 的表中。它应该根据 live 是否为真来更新 game_type 的值,但这个值永远不会被保存。

class AddGameTypeToGames < ActiveRecord::Migration

  class Game < ActiveRecord::Base
  end

  def up
    say "Adding game_type column to Games table"
    add_column :games, :game_type, :string, :null => false, :default => 'Demo'

    say_with_time "Migrating live value into game_type column" do
      rows_affected = 0
      Game.all.each do |game|
        if game.live
          game.update_attributes!(:game_type => 'Live')
          rows_affected += 1
        end
      end
      rows_affected
    end
  end
end

我最终通过将game.update_attributes!(:game_type =&gt; 'Live') 更改为Game.connection.execute("UPDATE games SET game_type='Live' where id = #{game.id}") 来实现此功能。

我想知道为什么要更新属性!行不通?我还有其他可以正常工作的迁移。包含模型应该阻止验证妨碍迁移。我尝试在迁移中的游戏模型上设置attr_accessible :game_type,但这不起作用。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 database-migration


    【解决方案1】:

    您必须在游戏模型上运行循环之前添加此行

    Game.reset_column_information
    Game.all.each do |game|
      ....
      ....
    

    有时您希望在迁移中添加一列并在之后立即填充它。在这种情况下,您需要调用 Base#reset_column_information 以确保模型具有添加新列后的最新列数据。

    ActiveRecord::Migration 的 API 文档中有一个示例。查找“更改表后使用模型”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多