我试图让我的头周围 inverse_of
,我不明白这一点。
这是什么生成的SQL的样子,如果有的话?
请问 inverse_of
选项表现出同样的行为,如果使用:的has_many
,: belongs_to的
和:has_many_and_belongs_to
抱歉,如果这是这样一个基本的问题。
我看到这个例子:
类播放器<的ActiveRecord :: Base的
的has_many:卡:inverse_of => :播放器
结束
一流的卡<的ActiveRecord :: Base的
belongs_to的:播放器,:inverse_of => :牌
结束
解决方案
从的文档 ,它似乎像:inverse_of
选项,以避免SQL查询,而不是生成它们的方法。这是一个提示的ActiveRecord使用通过关系再次获取它已经加载的数据来代替。
他们的例子:
类地下城与LT;的ActiveRecord :: Base的
的has_many:陷阱:inverse_of => :地牢
HAS_ONE:evil_wizard,:inverse_of => :地牢
结束
一流的陷阱<的ActiveRecord :: Base的
belongs_to的:地牢:inverse_of => :陷阱
结束
类EvilWizard<的ActiveRecord :: Base的
belongs_to的:地牢:inverse_of => :evil_wizard
结束
在这种情况下,调用 dungeon.traps.first.dungeon
应该返回装货原始的地牢
对象,而不是一个新的一个作为将是默认的情况
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
解决方案
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.