我有困難的包裹我的腦海裏圍繞必要協會爲以下情況:如何使用單個表設置模型和其他幾個模型之間的HABTM關係?
我有一個「上傳」,它可以連接到任何一個「人」,一個 「組」,一「項目」或「辦公室」。
的上傳必須屬於多個人,團體,或在同一時間項目(即:它可以鏈接到兩個人,三個項目,其中一組,兩個辦事處。)
一個人,一個項目,一個組或一個項目可以有多個與他們相關的上傳。
我希望能夠抓取與對象關聯的所有上傳(例如:@project.uploads)以及上傳鏈接到的所有項目(在一個方法中,比如@upload .linked_to)
我試圖避免創建一個表中的每個可能的關聯(projects_uploads,people_uploads,offices_uploads),我想它更靈活,因爲有可能是其他車型我想鏈接上傳到將來。
一個多態的關聯可能是我需要的......但我還沒有找到一個很像我試圖完成的例子。
有人能指出我正確的方向嗎?
謝謝!我可以嘗試澄清我的問題,如果有必要:)
編輯: 解決!這是我最後將其設置:
模型
Upload.rb
class Upload < ActiveRecord::Base
has_many :upload_connections
def linked # Shortcut for @upload.upload_connections
self.upload_connections
end
end
Upload_connection.rb
class UploadConnection < ActiveRecord::Base
belongs_to :uploadable, :polymorphic => true
belongs_to :upload
end
Project.rb/Office.rb/Person.rb等
class Project < ActiveRecord::Base
# (same for project, office, person, etc.)
has_many :upload_connections, :as => :uploadable
has_many :uploads, :through => :upload_connections
end
表結構
上傳
id: integer
filename: string
description: string
Upload_connections
id: integer
uploadable_id: integer
uploadable_type: string
upload_id: integer
...加上你想要關聯它們的任何對象的表格。
如果你爲每個連接添加一個sep列,它認爲這是可能的。但不太確定它是否可以被認爲是優秀的設計。 –
@MichaelSzyndel - 感謝您的回覆!使用多個表(projects_uploads,people_uploads,offices_uploads)並創建一個自定義方法來拉取屬於單個上傳的所有關係會更好嗎? – Andrew
上傳和項目/人員/辦公室多元化之間的這種關係? –