Created
May 9, 2010 16:56
-
-
Save neerajsingh0101/395267 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Given below is snippet from ActiveRecord page. | |
# class Dungeon < ActiveRecord::Base | |
# has_many :traps, :inverse_of => :dungeon | |
# has_one :evil_wizard, :inverse_of => :dungeon | |
# end | |
# | |
# class Trap < ActiveRecord::Base | |
# belongs_to :dungeon, :inverse_of => :traps | |
# end | |
# | |
# class EvilWizard < ActiveRecord::Base | |
# belongs_to :dungeon, :inverse_of => :evil_wizard | |
# end | |
# There are limitations to <tt>:inverse_of</tt> support: | |
# | |
# * does not work with <tt>:through</tt> associations. | |
# * does not work with <tt>:polymorphic</tt> associations. | |
# * for +belongs_to+ associations +has_many+ inverse associations are ignored. | |
# This is what I did. | |
create_table :dungeons do |t| | |
t.string :name | |
end | |
create_table :traps do |t| | |
t.string :name | |
t.integer :dungeon_id | |
end | |
create_table :evil_wizards do |t| | |
t.string :name | |
t.integer :dungeon_id | |
end | |
class Dungeon < ActiveRecord::Base | |
has_many :traps, :inverse_of => :dungeon | |
has_one :evil_wizard, :inverse_of => :dungeon | |
end | |
class EvilWizard < ActiveRecord::Base | |
belongs_to :dungeon, :inverse_of => :evil_wizard | |
end | |
class Trap < ActiveRecord::Base | |
belongs_to :dungeon, :inverse_of => :trap | |
end | |
class Dungeon | |
def self.cleanup | |
d = Dungeon.create(:name => 'boom') | |
Trap.create(:name => 'trap', :dungeon_id => d.id) | |
EvilWizard.create(:name => 'dragon', :dungeon_id => d.id) | |
end | |
def self.has_one_test | |
self.cleanup | |
dungeon = Dungeon.first | |
puts dungeon.object_id | |
evil_wizard = EvilWizard.first | |
puts evil_wizard.dungeon.object_id | |
end | |
def self.has_many_test | |
self.cleanup | |
dungeon = Dungeon.first | |
puts dungeon.object_id | |
trap = Trap.first | |
puts trap.dungeon.object_id | |
end | |
end | |
# Dungeon.has_one_test prints object_ids which are not same. | |
# rails runner 'Person.has_one_test' | |
# 2181166020 | |
# 2181157800 | |
# Dungeon.has_many_test blows up with following exception. | |
# `check_validity_of_inverse!': Could not find the inverse association for dungeon (:trap in Dungeon) # (ActiveRecord::InverseOfAssociationNotFoundError) | |
# Above example was tested with rails edge as of Mary 9th 2010. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment