当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - Model won't save changes when using Model.update_attributes! during Rails 3 migration

问题描述:

I have the following Rails 3 migration which adds a column game_type to a table called games. It's supposed to update the value of the game_type depending on whether live is true, but this value never gets saved.

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

I eventually got this to work by changing the line game.update_attributes!(:game_type => 'Live') to Game.connection.execute("UPDATE games SET game_type='Live' where id = #{game.id}").

I'm wondering why update_attributes! wouldn't work? I have other migrations where this works fine. Including the model is supposed to stop validations getting in the way of the migration. I tried setting attr_accessible :game_type on the Game model in the migration, but this didn't work.

网友答案:

you have to add this line before running the loop on Game model

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

Sometimes you’ll want to add a column in a migration and populate it immediately after. In that case, you’ll need to make a call to Base#reset_column_information in order to ensure that the model has the latest column data from after the new column was added.

There's an example of this in the API docs for ActiveRecord::Migration. Look for "Using a model after changing its table"

分享给朋友:
您可能感兴趣的文章:
随机阅读: