我正在为 rails 和 db:migrate 苦苦挣扎。我有一个使用此代码的迁移
class SetDefaultInstallmentsForLicenses < ActiveRecord::Migration
def up
License.where(code: 'LEADER').each do |leader|
puts "Modifying license #{leader.id} with code #{leader.code}"
leader.installment_available = true
leader.installment_number = 5
leader.save
puts "After save #{leader.installment_available} #{leader.installment_number}"
leader = License.find(leader.id)
puts "After save #{leader.installment_available} #{leader.installment_number}"
end
end
def down
end
end
运行迁移后有这个输出
== SetDefaultInstallmentsForLicenses: migrating ==============================
Modifying license 3 with code LEADER
After save true 5
After save f
== SetDefaultInstallmentsForLicenses: migrated (0.0037s) =====================
可以清楚的看到执行了迁移,找到了记录,更改并保存了,但是重新加载记录后,更改没有了。 怎么了?
最佳答案
leader.save
puts "After save #{leader.installment_available} #{leader.installment_number}"
==> After save true 5
以上仅显示 local variable leader
中的 installment_available
和 installment_number
字段的值,并未从数据库中提取值。 这并不意味着字段已成功保存在数据库中。
leader = License.find(leader.id)
puts "After save #{leader.installment_available} #{leader.installment_number}"
但是上面是从数据库中获取记录并清楚地表明更新没有保存在数据库中。
代替 leader.save
,使用 leader.save!
。这样,如果记录没有保存,那么您将确切知道为什么它因为引发的异常而没有保存。
更新
根据OP对这个问题的回答
I tried to put
License.reset_column_information
before the code and it seems to be working now. I don't have clue why this is needed here. All my other migrations seem to be working properly.
我做了一些研究 License.reset_column_information
到底做了什么。我找到了 Using Models in Your Migrations 上面写着:
When using a local model, it's a good idea to call Product.reset_column_information to refresh the Active Record cache for the Product model prior to updating data in the database.
希望这能帮助您理解为什么需要 License.reset_column_information
。
关于ruby-on-rails - 使用 rake db :migrate does not change it 迁移数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23447458/