【问题标题】:ActiveRecord is resetting all my previously defined variablesActiveRecord 正在重置我之前定义的所有变量
【发布时间】:2016-05-11 22:47:59
【问题描述】:

我正在构建一个 rake 任务,以便在两个数据库之间迁移一些数据。它们具有完全相同的结构。我的任务是这样的:

namespace :oab_nexus_migration do
  task :start, [:oab_user, :nexus_user] => :environment do |t, args|
    oab_account      = User.find_by_username(args[:oab_user]).main_account

    oab_trials       = oab_account.trials.includes(:parts)
    oab_schedules    = oab_account.schedules
    oab_movements    = oab_account.movements
    oab_annotations  = oab_account.annotations
    oab_hearings     = oab_account.hearings
    oab_publications = oab_account.publications
    oab_tasks        = oab_account.tasks
    oab_people       = oab_account.people.includes(:addresses, :internet_addresses, :phones)

    ActiveRecord::Base.establish_connection(:other_database)

    ...
    More code here
  end
end

任务执行时:

RAILS_ENV=production rake oab_nexus_migration:start[user_one, user_two]

从数据库一中检索到我需要的所有信息后,我需要将其插入到数据库二中。但真正奇怪的事情正在发生。例如,如果我在establish_connection 之前调用p oab_trials(或任何其他变量),则所有值都在那里,由一个大数组表示。但是如果我尝试在establish_connection 之后调用它,返回的值是一个空数组。似乎 ActiveRecord 正在重置我之前定义的所有变量。

这里发生了什么?

【问题讨论】:

  • 您可能想要制作两个不同但相似的模型来移植数据,每个数据库一个。

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


【解决方案1】:

您引用的相关集合是 ActiveRecord::Relation 的惰性求值实例。如果您的数据库连接在中途更改,则延迟评估不起作用。

在切换连接之前,您需要先将这些关系加载到内存中。在关系上调用.to_a 以强制执行此操作。

oab_account      = User.find_by_username(args[:oab_user]).main_account

oab_trials       = oab_account.trials.includes(:parts).to_a
oab_schedules    = oab_account.schedules.to_a
oab_movements    = oab_account.movements.to_a
oab_annotations  = oab_account.annotations.to_a
oab_hearings     = oab_account.hearings.to_a
oab_publications = oab_account.publications.to_a
oab_tasks        = oab_account.tasks.to_a
oab_people       = oab_account.people.includes(:addresses, :internet_addresses, :phones).to_a

【讨论】:

    【解决方案2】:

    oab_account.trials.includes(:parts) 不存储值,它存储对延迟评估的ActiveRecord::Relation 的引用。

    所以不是ActiveRecord 正在重置变量的值,而是当您连接到第二个数据库时,您正在更改对空集合的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-07
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 2015-04-08
      相关资源
      最近更新 更多