Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails: Tables Finder
# Example:
#
# > TablesFinder.call(column_name: 'site_id')
# => ['events', 'users']
class TablesFinder
VALID_ATTRIBUTES = %w[
COLUMN_NAME
].freeze
def self.call(args)
new(args).call
end
def initialize(args)
@matcher_attribute = args.keys.first.to_s.upcase
@matcher_value = args.values.first.to_s.downcase
end
def call
return [] unless [matcher_attribute, matcher_value].all?
return [] unless matcher_attribute.in?(VALID_ATTRIBUTES)
find_tables
end
private
attr_reader :matcher_attribute, :matcher_value
def find_tables
ActiveRecord::Base.connection.execute(
"SELECT table_name FROM INFORMATION_SCHEMA.COLUMNS
WHERE #{matcher_attribute} = '#{matcher_value}'
ORDER BY TABLE_NAME"
).values.flatten
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.