2013-10-18 24 views
0

我在Rails應用程序中有以下模型。Rails從關係中訪問多態數據

class Address < ActiveRecord::Base 
    belongs_to :addressable, :polymorphic => true 
end 

class Client < ActiveRecord::Base 
    has_one :address, :as => :addressable, dependent: :destroy 
    accepts_nested_attributes_for :address, :allow_destroy => true 

    has_many :invoices 
end 

class Invoice < ActiveRecord::Base 
    belongs_to :client 
end 

雖然我能夠使用

@invoice.client.name 

檢索客戶名,我不能夠檢索以類似方式的地址信息。

如何檢索發票視圖中的地址屬性?

+0

@ invoice.client.address –

回答

0

@ invoice.client.address這是aswer。但我建議你遵循迪米特法則使用方法委託

http://en.wikipedia.org/wiki/Law_of_Demeter
http://api.rubyonrails.org/classes/Module.html#method-i-delegate

基本上想法是,你可以這樣做:@ invoice.client.address_streetØ更好@invoice。 client_address_street

+0

謝謝。我曾嘗試過,並沒有奏效。現在我發現問題在於我創建的種子數據,其中客戶端未鏈接到地址。無論如何,我必須熟悉德米特法,而且我已經實現了這一點。謝謝! –