What does inverse_of do? What SQL does it generate?

Federico picture Federico · Feb 15, 2012 · Viewed 43.8k times · Source

I'm trying to get my head around inverse_of and I do not get it.

What does the generated sql look like, if any?

Does the inverse_of option exhibit the same behavior if used with :has_many, :belongs_to, and :has_many_and_belongs_to?

Sorry if this is such a basic question.

I saw this example:

class Player < ActiveRecord::Base
  has_many :cards, :inverse_of => :player
end

class Card < ActiveRecord::Base
  belongs_to :player, :inverse_of => :cards
end

Answer

tadman picture tadman · Feb 15, 2012

From the documentation, it seems like the :inverse_of option is a method for avoiding SQL queries, not generating them. It's a hint to ActiveRecord to use already loaded data instead of fetching it again through a relationship.

Their example:

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

In this case, calling dungeon.traps.first.dungeon should return the original dungeon object instead of loading a new one as would be the case by default.