Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created October 3, 2008 18:13
Show Gist options
  • Save nakajima/14600 to your computer and use it in GitHub Desktop.
Save nakajima/14600 to your computer and use it in GitHub Desktop.
Shows the other records that get destroyed when you destroy this one.
class ActiveRecord::Base
def dependents(type=:destroy)
reflections = self.class.reflect_on_all_associations
reflections = reflections.select { |r| r.options[:dependent] == type }
names = reflections.map(&:name)
names.inject([]) do |list, name|
list += send(name)
list += send(name).map { |entity| entity.dependents rescue [] }
list
end.flatten.compact
end
def inspect_dependents
dependents.inject({ }) do |memo, entity|
name = entity.class.name.tableize
memo[name] ||= []
memo[name] << entity
memo
end
end
end
class User < ActiveRecord::Base
has_many :lists, :dependent => :destroy
has_many :things # not dependent, so won't show up in results
end
class List < ActiveRecord::Base
belongs_to :user
has_many :items, :dependent => :destroy
end
class Item < ActiveRecord::Base
belongs_to :list
end
# Should not show up in dependents list
class Thing < ActiveRecord::Base
belongs_to :user
end
# creates seed data in script console
def create_seed_data
print "=> creating seed data... "
user = User.create!
list = user.lists.create!
list.items.create!
list.items.create!
user.things.create! # won't be in results
puts "done!"
end
>> create_seed_data
=> creating seed data... done!
=> nil
>> user = User.first
=> #<User id: 1, name: nil, created_at: "2008-10-03 19:14:17", updated_at: "2008-10-03 19:14:17">
>> user.dependents
=> [#<List id: 1, user_id: 1, created_at: "2008-10-03 19:14:17", updated_at: "2008-10-03 19:14:17">, #<Item id: 1, list_id: 1, created_at: "2008-10-03 19:14:17", updated_at: "2008-10-03 19:14:17">, #<Item id: 2, list_id: 1, created_at: "2008-10-03 19:14:17", updated_at: "2008-10-03 19:14:17">]
>> user.inspect_dependents
=> {"items"=>[#<Item id: 1, list_id: 1, created_at: "2008-10-03 19:14:17", updated_at: "2008-10-03 19:14:17">, #<Item id: 2, list_id: 1, created_at: "2008-10-03 19:14:17", updated_at: "2008-10-03 19:14:17">], "lists"=>[#<List id: 1, user_id: 1, created_at: "2008-10-03 19:14:17", updated_at: "2008-10-03 19:14:17">]}
>> y _
---
items:
- &id001 !ruby/object:Item
attributes:
updated_at: 2008-10-03 19:14:17
id: "1"
list_id: "1"
created_at: 2008-10-03 19:14:17
attributes_cache: {}
- &id002 !ruby/object:Item
attributes:
updated_at: 2008-10-03 19:14:17
id: "2"
list_id: "1"
created_at: 2008-10-03 19:14:17
attributes_cache: {}
lists:
- !ruby/object:List
attributes:
updated_at: 2008-10-03 19:14:17
id: "1"
user_id: "1"
created_at: 2008-10-03 19:14:17
attributes_cache: {}
items:
- *id001
- *id002
=> nil
>> exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment