Any rails plugins / jewels for detecting lost entries?

Look for something that can go through the relationships defined in the models, and you can check the DB for lost records / broken links between tables.

+3
source share
8 answers

This may depend on what action you want to take with the orphans. Perhaps you just want to delete them? This is easily resolved with a few SQL queries.

+2
source

(for the latest version of the script below, see https://gist.github.com/KieranP/3849777 )

Martin script , ActiveRecord , , . SQL . , 100- 5+ _to, 10 + .

script SQL, belongs_to / Rails. sort_to, belongs_to : class_name . , , Martin script 9 8 , , .

: -)

task :orphaned_check => :environment do

  Dir[Rails.root.join('app/models/*.rb').to_s].each do |filename|
    klass = File.basename(filename, '.rb').camelize.constantize
    next unless klass.ancestors.include?(ActiveRecord::Base)

    orphanes = Hash.new

    klass.reflect_on_all_associations(:belongs_to).each do |belongs_to|
      assoc_name, field_name = belongs_to.name.to_s, belongs_to.foreign_key.to_s

      if belongs_to.options[:polymorphic]
        foreign_type_field = field_name.gsub('_id', '_type')
        foreign_types = klass.unscoped.select("DISTINCT(#{foreign_type_field})")
        foreign_types = foreign_types.collect { |r| r.send(foreign_type_field) }

        foreign_types.sort.each do |foreign_type|
          related_sql = foreign_type.constantize.unscoped.select(:id).to_sql

          finder = klass.unscoped.select(:id).where("#{foreign_type_field} = '#{foreign_type}'")
          finder.where("#{field_name} NOT IN (#{related_sql})").each do |orphane|
            orphanes[orphane] ||= Array.new
            orphanes[orphane] << [assoc_name, field_name]
          end
        end
      else
        class_name = (belongs_to.options[:class_name] || assoc_name).classify
        related_sql = class_name.constantize.unscoped.select(:id).to_sql

        finder = klass.unscoped.select(:id)
        finder.where("#{field_name} NOT IN (#{related_sql})").each do |orphane|
          orphanes[orphane] ||= Array.new
          orphanes[orphane] << [assoc_name, field_name]
        end
      end
    end

    orphanes.sort_by { |record, data| record.id }.each do |record, data|
      data.sort_by(&:first).each do |assoc_name, field_name|
        puts "#{record.class.name}##{record.id} #{field_name} is present, but #{assoc_name} doesn't exist"
      end
    end
  end

end
+3

Rake , :

namespace :db do
  desc "Handle orphans"
  task :handle_orphans => :environment do
    Dir[Rails.root + "app/models/**/*.rb"].each do |path|
      require path
    end
    ActiveRecord::Base.send(:descendants).each do |model|
      model.reflections.each do |association_name, reflection|
        if reflection.macro == :belongs_to
          model.all.each do |model_instance|
            unless model_instance.send(reflection.primary_key_name).blank?
              if model_instance.send(association_name).nil?
                print "#{model.name} with id #{model_instance.id} has an invalid reference, would you like to handle it? [y/n]: "
                case STDIN.gets.strip
                  when "y", "Y"
                    # handle it
                end
              end
            end
          end
        end
      end
    end
  end
end
+1

, , . ActiveRecord :

    # app/models/subscription.rb
    class Subscription < ActiveRecord::Base
      belongs_to :magazine
      belongs_to :user
    end

    # app/models/user.rb
    class User < ActiveRecord::Base
      has_many :subscriptions
      has_many :users, through: :subscriptions
    end

    # app/models/magazine.rb
    class Magazine < ActiveRecord::Base
      has_many :subscriptions
      has_many :users, through: :subscriptions
    end

, - :: destroy has_many: subscriptions. , .

:: destroy, - . .

1 -

Subscription.find_each do |subscription|
  if subscription.magazine.nil? || subscription.user.nil?
    subscription.destroy
  end
end

SQL- , , , , .

2 -

Subscription.where([
  "user_id NOT IN (?) OR magazine_id NOT IN (?)",
  User.pluck("id"),
  Magazine.pluck("id")
]).destroy_all

, , , , .

+1

KieranP , script . , . DELETE = true, .

namespace :db do
  desc "Find orphaned records. Set DELETE=true to delete any discovered orphans."
  task :find_orphans => :environment do

    found = false

    model_base = Rails.root.join('app/models')

    Dir[model_base.join('**/*.rb').to_s].each do |filename|

      # get namespaces based on dir name
      namespaces = (File.dirname(filename)[model_base.to_s.size+1..-1] || '').split('/').map{|d| d.camelize}.join('::')

      # skip concerns folder
      next if namespaces == "Concerns"

      # get class name based on filename and namespaces
      class_name = File.basename(filename, '.rb').camelize
      klass = "#{namespaces}::#{class_name}".constantize

      next unless klass.ancestors.include?(ActiveRecord::Base)

      orphans = Hash.new

      klass.reflect_on_all_associations(:belongs_to).each do |belongs_to|
        assoc_name, field_name = belongs_to.name.to_s, belongs_to.foreign_key.to_s

        if belongs_to.options[:polymorphic]
          foreign_type_field = field_name.gsub('_id', '_type')
          foreign_types = klass.unscoped.select("DISTINCT(#{foreign_type_field})")
          foreign_types = foreign_types.collect { |r| r.send(foreign_type_field) }

          foreign_types.sort.each do |foreign_type|
            related_sql = foreign_type.constantize.unscoped.select(:id).to_sql

            finder = klass.unscoped.where("#{foreign_type_field} = '#{foreign_type}'")
            finder.where("#{field_name} NOT IN (#{related_sql})").each do |orphan|
              orphans[orphan] ||= Array.new
              orphans[orphan] << [assoc_name, field_name]
            end
          end
        else
          class_name = (belongs_to.options[:class_name] || assoc_name).classify
          related_sql = class_name.constantize.unscoped.select(:id).to_sql

          finder = klass.unscoped
          finder.where("#{field_name} NOT IN (#{related_sql})").each do |orphan|
            orphans[orphan] ||= Array.new
            orphans[orphan] << [assoc_name, field_name]
          end
        end
      end

      orphans.sort_by { |record, data| record.id }.each do |record, data|
        found = true
        data.sort_by(&:first).each do |assoc_name, field_name|
          puts "#{record.class.name}##{record.id} #{field_name} is present, but #{assoc_name} doesn't exist" + (ENV['DELETE'] ? ' -- deleting' : '')
          record.delete if ENV['DELETE']
        end
      end
    end

    puts "No orphans found" unless found
  end
end
+1

:

Product.where.not(category_id: Category.pluck("id")).delete_all

, .

+1

OrphanRecords. / . HABTM, , , :)

0

, PolyBelongsTo

, pbt_orphans ActiveRecord.

Gemfile

gem 'poly_belongs_to'

User.pbt_orphans
# => #<ActiveRecord::Relation []> # nil for objects without belongs_to
Story.pbt_orphans
# => #<ActiveRecord::Relation []> # nil for objects without belongs_to

.

, , : ?.

User.first.orphan?
Story.find(5).orphan?

, .

As a bonus, if you want to find polymorphic records with invalid types, you can do the following:

Story.pbt_mistyped

Returns an array of invalid ActiveRecord model name entries used in your Story entries. Entries with types such as ["Object", "Class", "Storytelling"].

0
source

Source: https://habr.com/ru/post/1783055/


All Articles