2016-12-09 182 views
1

我有一個相當具體的問題,所以我會把它翻譯成更容易理解和清晰的例子。如何將一個模型連接到另一個模型?

所以我們有'國家'和'圖像'模型。一個國家有它的旗幟和手臂。

這意味着我們必須將國家連接到圖像2次。我試圖改變Rails指南的配方'連接到自己',但是,我總是得到一個異常:「圖像預期,得到字符串」。

*Country model 
    class Country < ApplicationRecord 
    has_one :flag, class_name: 'Image', foreign_key: 'id' 
    has_one :arm, class_name: 'Image', foreign_key: 'id' 
    end 

*Image model 
    class Image < ApplicationRecord 
    belongs_to :flag, class_name: 'Country' 
    belongs_to :arm, class_name: 'Country' 
    end 

回答

5

您在Image模型中沒有任何內容來指定圖像是標記還是手臂。

所以,添加一列represents它可以是「標誌」或「武器」,並確保圖像具有country_id整型字段,然後設置關係,因爲......

class Image < ApplicationRecord 
    belongs_to :country 
end 

class Country < ApplicationRecord 
    has_one :flag, -> {where represents: 'flag'}, class_name: 'Image' 
    has_one :arms, -> {where represents: 'arms'}, class_name: 'Image' 
end 
+0

它的工作原理!非常感謝你! –

相關問題