inverse_of 有什么作用?它生成什么 SQL? [英] What does inverse_of do? What SQL does it generate?
问题描述
我正在尝试了解 inverse_of
,但我不明白.
I'm trying to get my head around inverse_of
and I do not get it.
生成的sql是什么样的,如果有的话?
What does the generated sql look like, if any?
如果与 :has_many
、:belongs_to
和 :has_many_and_belongs_to
一起使用,inverse_of
选项是否表现出相同的行为>?
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.
我看到了这个例子:
class Player < ActiveRecord::Base
has_many :cards, :inverse_of => :player
end
class Card < ActiveRecord::Base
belongs_to :player, :inverse_of => :cards
end
推荐答案
来自文档,看起来 :inverse_of
选项是一种避免 SQL 查询的方法,而不是生成它们.提示 ActiveRecord 使用已加载的数据,而不是通过关系再次获取它.
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.
他们的例子:
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
在这种情况下,调用 dungeon.traps.first.dungeon
应该返回原始的 dungeon
对象,而不是像默认情况那样加载一个新对象.
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.
这篇关于inverse_of 有什么作用?它生成什么 SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!