2009-09-18 84 views
2

嗨gys我想嘗試鏈接兩個實體的一個實體是管理機構,遺產和repo_document,然後管理機構可以repo_document該遺產也可以有,所以我決定創建一個加入名爲document_owner表..但我不知道該怎麼在他們models..i已經寫在了我的document_owner模型這個代碼..需要幫助與多態聯接表在軌道

belongs_to :repo_document 
belongs_to :estate, :through => :repo_document, :foreign_key => :owner_id, :conditions => "owner_type = 'Estate'" 
belongs_to :governing_body, :through => :repo_document, :foreign_key => :owner_id, :conditions => "owner_type = 'GoverningBody'" 
belongs_to :owner, :polymorphic => true 

而這個是我repo_document

has_and_belongs_to_many :owners, :join_table => :document_owners, :conditions =>  "owner_type = 'Estate' OR owner_type = 'GoverningBody'" 

,這一次在我的莊園

has_many :repo_documents, :source => :document_owners, :foreign_key => :owner_id, :conditions => "owner_type = 'Estate' " 

而這個是我governing_body

has_many :repo_documents, :source => :document_owners, :foreign_key => :owner_id, :conditions => "owner_type = 'GoverningBody' " 

,但是當我試圖挽救它不保存連接表內的任何東西..

任何人可以幫助我,請

回答

4

正當的意見,我認爲多態連接表是一個非常糟糕的主意,應該避免除非絕對必要的。他們不僅難以正確索引,而且會讓涉及他們的每個查詢都變得更加複雜,而且難以擴展。理想情況下,您擁有的任何多態關聯將永遠不會用於將兩個表連接在一起。

此外,不推薦使用has_and_belongs_to_many,如果在大多數情況下使用has_many:through是更好的解決方案。

簡化這種方法的一種方法是將你的Estate和GoverningBody模型組合成一張表,也許使用STI來區分兩者。這樣文檔和這個特定實體之間的關係就更加明顯了。

如果這樣做不實際,那麼你最好有兩個簡單的連接表,而不是多態連接表。

多態協會最適合於一對多的偶然關係。例如:

class Example < ActiveRecord::Base 
    # This model has notes 
    has_many :notes, :as => :record 
end 

class Note 
    # Can be attached to any kind of record 
    belongs_to :record, :polymorphic => true 
end 

在這種情況下,Note可以附加到任何類型的記錄。重要的是,它不在關係中使用,它是一個終點。

+1

對於類似於圖像的東西,您可能會附加到多個對象,例如「事件」和「用戶?」,您有什麼建議? – 2013-02-04 19:46:34

+2

如果這些是外圍葉型實體,那麼使用複合關鍵字和多態關聯很可能就像這裏例子中的Note一樣。當在JOIN中使用這些關係時,最好擁有像user_images或event_images這樣的特殊用途表,因爲這些索引在導航和更新上要便宜得多。這些擔憂實際上只與規模有關,比如超過10^6條記錄。 – tadman 2013-02-04 20:33:43