ActiveRecord 属性消失的案例

The case of the disappearing ActiveRecord attribute

按照 中的说明,我得到了以下结果:

namespace :db do
  desc 'Drop, create, migrate, seed and populate sample data'
  task seed_sample_data: [:drop, :create, :migrate, :seed, :populate_sample_data] do
    puts 'Sample Data Populated. Ready to go!'
  end

  desc 'Populate the database with sample data'
  task populate_sample_data: :environment do
    puts Inspector.column_names.include?('how_to_fix')
    # create my sample data
  end
end

如您所料,如果我 运行 bundle exec rake db:populate_sample_data

,我会得到 true

但是如果我 运行 bundle exec rake db:seed_sample_data 我得到所有迁移输出然后 false。换句话说,我看不到 Inspector 属性 how_to_fix,即使它确实存在,正如另一个 rake 运行 所证明的那样。我的属性哪里去了?

我猜这是一个 "caching" 问题。您可以尝试以下方法吗?

task populate_sample_data: :environment do
  Inspector.reset_column_information
  # ...
end

P.S。我们曾经在使用具有完全相同模式的不同数据库时遇到过类似的问题(除了这里和那里的一些列)