【问题标题】:Map a table to the appropriate ActiveRecord::Model将表映射到适当的 ActiveRecord::Model
【发布时间】:2019-09-28 10:50:48
【问题描述】:

我想遍历我的所有数据库表并遍历我的数据库中的每条记录。我目前正在实现这一点:

ActiveRecord::Base.connection.tables.each do |table|

  table.classify.constantize.find_each do |record|
  end

  rescue NameError
end

问题在于它会像这样拉表:ar_internal_metadataschema_migrations 没有相应的模型,因此,我的 table.classify.constantize 失败并出现 NameError 这就是为什么我要在底端。

我不想挽救这个错误。那么,有没有办法可以将表映射到适当的 ActiveRecord::Model?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    忽略所有不存在的模型很容易出错。相反,我建议只忽略您不希望有相应模型的表。

    RAILS_META_TABLES = %w[ar_internal_metadata schema_migrations]
    
    ActiveRecord::Base.connection.tables.each do |table|
      next if RAILS_META_TABLES.include?(table)
    
      table.classify.constantize.find_each do |record|
        # ...
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 2018-07-03
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多