2016-05-18 46 views
1

我在查看一些代碼,我看到delegatehas_many + through被用來代替設置一個附加的關聯。我想知道使用delegate的好處在於設置另一個has_many關聯。使用委託而不是在Rails中構建關聯。重點是什麼?

class AppleCore 
    belongs_to :apple 
    delegate :tree to :apple 
end 

然後

class Apple 
    belongs_to :tree 
end 

最後

class Tree 
    has_many :apples 
end 

在這個例子......爲什麼我們只是委託樹的蘋果,而不是創造AppleCore與樹之間的關聯?

回答

0

它允許您使代碼更具可讀性。您可以撥打apple_core.tree而不是apple_core.apple.tree。其中apple_core是AppleCore的一個實例。如果你設置前綴爲真,delegate :tree to :apple, prefix: true。您將使用apple_core.apple_true進行訪問。

欲瞭解更多信息結賬Rails Api Documentation

相關問題