Bitwise
Bitwise

Reputation: 8461

Map a table to the appropriate ActiveRecord::Model

I want to loop through all of my Database tables and iterate through each record in my Database. I'm achieving this currently like so:

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

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

  rescue NameError
end

The problem is that it pulls table like this: ar_internal_metadata and schema_migrations which don't have corresponding models so, therefore, my table.classify.constantize fails with a NameError which is why I'm rescuing that at the bottom.

I'd like to not have to rescue that error. So, is there a way I can map a table to the appropriate ActiveRecord::Model?

Upvotes: 0

Views: 175

Answers (1)

spickermann
spickermann

Reputation: 106802

Just ignoring all non-existing models is error prone. Instead, I suggest to only ignore tables you expect not to have a corresponding model.

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

Upvotes: 1

Related Questions