2013-02-18 27 views
13

由於這裏概述:爲什麼我不想在所有地方使用inverse_of?

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

inverse_of似乎告訴Rails來緩存在內存中協會和儘量減少數據庫查詢。他們的例子是:

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 

,他們立刻與遵循:

for `belongs_to` associations `has_many` inverse associations are ignored. 

所以我有幾個問題。

  1. has_many對於belongs_to被忽略的逆關聯?如果是這樣,他們的榜樣是如何理解的?難道它不應該做任何事情嗎?
  2. 據我可以告訴(假設它沒有做任何事情),這一切都讓做的是一樣的東西:

    dungeon.traps.first.dungeon 
    

    一起.dungeon最後通話不產生一個全新的查詢,而僅僅是深遠的在內存關聯中。假設這是正確的,爲什麼我不想要這種行爲?爲什麼我不會在每個關聯上堅持inverse_of:

回答

6

我開始寫關於軌道偏移器的內容,以及關聯如何不是一個使用inverse_of來指示它是什麼的模型的直接變形。但後來我滾動到你提到的部分,這是我看到它的方式。假設你有這樣的:

# let's pick a dungeon 
d = Dungeon.first 

# say you find also find a trap that belongs to this particular d 
t = Trap.find(...) 

# then t.dungeon is the exact same object as d 
d == t.dungeon 

當然dungeon.traps.first.dungeon並不真正意義,我懷疑這就是爲什麼它存在。就我個人而言,我不知道我會在哪裏以及如何使用它,但他們給出的例子似乎填補了用例。它是這樣的:

# you have an attribute level on dungeon 
d.level # => 5 

# now say you have a comparison after a modification to level 
d.level = 10 

# now without inverse_of the following thing occurs 
d.level   # => 10 
t.dungeon.level # => 5 

# d was updated and since t.dungeon is a whole different object 
# it doesn't pick up the change and is out of sync but using invers_of you get 
d.level   # => 10 
t.dungeon.level # => 10 

# because d and t.dungeon are the very same object 

希望澄清事情。

+0

這是否意味着,如果我說了(而不是d.level = 10)t.dungeon.level = 10,即d.level不會得到更新,即使如果我設置inverse_of,因爲它被忽略?一般來說,更新集合的成員不會同步到該成員的其他實例?但至少在希望他們最終支持它的時候,似乎並沒有把問題推到任何地方,對吧? – bdwain 2013-04-18 06:59:12

+0

@bdwain這對我來說很有意思,因爲我總是認爲Rails會自動推斷出這種'inverse_of'關係(如果名字匹配)。在最近出現這種情況後(同時在一個相關模型的accept_nested_attributes_for模型上進行驗證),我必須同意你的結論:慷慨地使用'inverse_of'。我無法想象任何理由。 – steve 2013-11-25 22:57:03

4

好消息!在Rails 4.1基礎協會*會自動設置inverse_of

*更多的便利意味着更多的邊緣情況... 自動inverse_of 作品是做協會不指定任何下列選項:

  • :through
  • :foreign_key
  • :conditions
  • :polymorphic

資源:

http://edgeguides.rubyonrails.org/4_1_release_notes.html http://wangjohn.github.io/activerecord/rails/associations/2013/08/14/automatic-inverse-of.html

+0

手冊中的「不適用於:條件」不完全正確,應該是「不定義範圍」。 – 244an 2016-05-20 23:53:55

相關問題