为什么 rails 文档说要将 inverse_of 放在 belongs_to 关系上

why rails docs says to put inverse_of on a belongs_to relation

为什么 rails docs 说要在 has_* - belongs_to 关系中使用 inverse_of

class Customer < ActiveRecord::Base
  has_many :orders, inverse_of: :customer
end

class Order < ActiveRecord::Base
  belongs_to :customer, inverse_of: :orders
end

无论如何,在玩 rails 时,当您将 inverse_of 放入 belongs_to 关联时,我可以看到它会引发错误。我的观察是否正确(文档没有抓住重点)还是我做错了什么?

结果是我的错字 + 一个 IDE 神奇的东西让我以为它是 rails 东西。

why rails docs says to put inverse_of on a belongs_to relation

这是为了在获取关联记录时进行内存优化。默认情况下,关联对象不会指向相同的内存中对象。因此,无论何时在 :belongs_to:has_many 关联上执行 order.customer 而没有 inverse_of,它都会访问数据库。使用 :inverse_of,如果我们已经在内存中有该客户记录,那么 order.customer 将指向同一个客户。

详细参考:http://viget.com/extend/exploring-the-inverse-of-option-on-rails-model-associations