Skip to content

Instantly share code, notes, and snippets.

@ixti
Created October 21, 2021 02:26
Show Gist options
  • Save ixti/da07211cc02dc1bb416a866f8d1e3864 to your computer and use it in GitHub Desktop.
Save ixti/da07211cc02dc1bb416a866f8d1e3864 to your computer and use it in GitHub Desktop.
Print missing options for ActiveRecord associations
require_relative "config/environment"
Rails.application.eager_load!
Rails.root.glob("app/models/**/*.rb").each { |f| require_relative f }
has_xxx_required_options = %i[dependent inverse_of].freeze
belongs_to_required_options = %i[inverse_of].freeze
needs = Hash.new { |h, k| h[k] = Set.new }
ActiveRecord::Base.descendants.each do |klass|
klass.reflections.each_value do |reflection|
case reflection
when ActiveRecord::Reflection::HasOneReflection, ActiveRecord::Reflection::HasManyReflection
has_xxx_required_options.each { |key| needs[key] << reflection unless reflection.options[key] }
when ActiveRecord::Reflection::BelongsToReflection
belongs_to_required_options.each { |key| needs[key] << reflection unless reflection.options[key] }
when ActiveRecord::Reflection::ThroughReflection
# do nothing
else
raise "dunno about #{reflection.inspect}"
end
end
end
needs.each do |option, reflections|
puts "\n\n= MISSING `:#{option}`\n\n"
reflections.group_by { |it| it.active_record.name }.sort_by(&:first).each do |model, arr|
arr.each do |reflection|
puts "* #{model}.#{reflection.macro}(:#{reflection.name})"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment