Skip to content

Instantly share code, notes, and snippets.

@giacomomacri
Last active March 30, 2018 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giacomomacri/d54f97b0a5d954930693a1d211582209 to your computer and use it in GitHub Desktop.
Save giacomomacri/d54f97b0a5d954930693a1d211582209 to your computer and use it in GitHub Desktop.
A simple rails concern for checking if a record is referenced in some foreign_key (by id)
module ForeignKeysCheck
extend ActiveSupport::Concern
def has_foreign_key_references?
self.class.all_constraints.group_by {|c| c["table_name"] }.each do |table_name, constraints|
check_query = "SELECT 1 from #{table_name} WHERE "
check_query << constraints.map { |d| "#{d['column_name']} = #{self.id}" }.join(' OR ')
result = ActiveRecord::Base.connection.execute(check_query)
result.count
return true if result.count > 0
end
false
end
class_methods do
def all_constraints
@all_constraints ||= ActiveRecord::Base.connection.execute <<-SQL
SELECT
tc.table_schema, tc.constraint_name, tc.table_name, kcu.column_name, ccu.table_name
AS foreign_table_name, ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND ccu.table_name = '#{self.table_name}'
SQL
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment