2012-01-24 50 views
3

我繼承其具有代碼:ror - 包含has_many和belongs_to兩端的外鍵?

class Graphic < ActiveRecord::Base 
    has_many :comments, :foreign_key => 'asset_id', 
    :conditions => 'asset_type_id = 5', 
    :order => 'created_at', :dependent => :destroy 

class Comment < ActiveRecord::Base 
    belongs_to :graphic, :foreign_key => :asset_id 

在我看來,像的has_many不應該有foreign_key(它在belongs_to的引用好,我相信),但我不知道,你知道嗎?

即它應該是

class Graphic < ActiveRecord::Base 
    has_many :comments, 
    :conditions => 'asset_type_id = 5', 
    :order => 'created_at', :dependent => :destroy 

class Comment < ActiveRecord::Base 
    belongs_to :graphic, :foreign_key => :asset_id 

回答

3

我認爲你正在嘗試做一些已經在Rails中烘焙的東西。你應該在這裏使用Polymorphic Associations。

class Comment 
    belongs_to :asset, :polymorphic => true 
end 

class Graphic 
    has_many :comments, :as => :assets 
end 

這樣你就不需要聲明foreign_key。

+0

這也是如此......我只是想回答他的問題哈哈。 – Batkins

3

has_many聲明鋼軌,:foreign_key確實是其在ActiveRecord documentation這說明一個選項:

指定用於關聯的外鍵。默認情況下,這被認爲是這個類的名字,小寫和「_id」後綴。因此,一個使has_many關聯的Person類將使用「person_id」作爲默認值:foreign_key。

所以你的情況,它看起來好像你需要在你的has_many聲明foreign_key屬性,因爲它從類的名稱不同。

但是,你不應該需要在belongs_to聲明foreign_key聲明。下面是在the ActiveRecord documentation:foreign_key選項的belongs_to關係描述:

指定用於關聯的外鍵。默認情況下,這被猜測爲帶有「_id」後綴的關聯的名稱。所以定義belongs_to:person關聯的類將使用「person_id」作爲默認值:foreign_key。類似地,belongs_to:favorite_person,:class_name =>「Person」將使用「favorite_person_id」的外鍵。

我假設你真正的意思是寫你的Comment類是這樣的:

class Comment < ActiveRecord::Base 
    belongs_to :graphic, :foreign_key => :graphic_id 

在這種情況下,你可以簡化belongs_to語句簡單:

belongs_to :graphic 
+0

我認爲他真的意味着asset_id,它可能會或可能不是圖形 –

+0

這兩個引號過於相似。我不明白爲什麼':foreign_key'在具有'has_many'的模型中被覆蓋,當它是具有'belongs_to'的模型時,它實際上具有外鍵在它的表中。 – mmcrae