ruby-on-rails - 使用 rake db :migrate does not change it 迁移数据

标签 ruby-on-rails ruby database-migration dbmigrate

我正在为 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_availableinstallment_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/

相关文章:

ruby-on-rails - 在 rails 中查找 gem 的完整路径

ruby-on-rails - 为什么嵌入式 ruby​​ 不能在公用文件夹的静态页面中工作?

ruby - 为什么 UnboundMethod 没有实例方法 `source` 因为它有 `source location` ?我该如何破解这个?

javascript - 如何为数据库实现 sequelize 向下迁移功能?

ruby-on-rails - 如何避免法拉第请求编码获取参数?

mysql - 当我在 Ruby on Rails 应用程序中转储 MySQL 表中的数据时,为什么它会显示特殊字符?

ruby module_function 与包含模块

ruby-on-rails - 点击 Google Contacts API 时出现 "connection reset by peer"错误

sql-server-2008 - 从 SQL Server 2000 迁移到 SQL Server 2008

mysql - 拉维尔 : How can I change default indexing key length in morph table