3

閱讀Ruby on Rails指南和一些關於多態關聯問題的stackoverflow響應之後,我瞭解了它的使用和實現,但我對特定的使用場景有疑問。我有可與多個topicscategoriesimages和其它各種型號(其也具有不同的tags)相關聯,但代替tags表內放置參考字段(foreign_idforeign_typetags,我寧願創建一個單獨的關聯表。這仍然可以使用:polymorphic => true獨立多態關聯表

事情是這樣的:

create_table :tags do |t| 
    t.string :name 
    t.remove_timestamps 
end 

create_table :object_tags, :id => false do |t| 
    t.integer :tag_id 
    t.references :tagable, :polymorphic => true 
    t.remove_timestamps 
end 

如果這是不可能的,我打算創建相同:object_tags表,並使用:conditionsTag模式與其他模式中,迫使協會。有沒有軌道這樣做?謝謝! (有軌3.0.9 &紅寶石1.8.7 <工作 - 因爲部署服務器仍在使用1.8.7)

UPDATE: 感謝Delba! Answer是HABTM多態性的工作解決方案。

class Tag < ActiveRecord::Base 
    has_many :labels 
end 

class Label < ActiveRecord::Base 
    belongs_to :taggable, :polymorphic => true 
    belongs_to :tag 
end 

class Topic < ActiveRecord::Base 
    has_many :labels, :as => :taggable 
    has_many :tags, :through => :labels 
end 

create_table :tags, :timestamps => false do |t| 
    t.string :name 
end 

create_table :labels, :timestamps => false, :id => false do |t| 
    t.integer :tag_id 
    t.references :taggable, :polymorphic => true 
end 

UPDATE:因爲我需要雙向HABTM,我最終要回創建單獨的表。

+0

你爲什麼想這樣呢? (純粹的好奇心,沒有判斷力) – Damien

+0

讓一個單一的表格具有所有可用於「標籤」的關聯,而不是爲每個模型的關聯創建單獨的表格似乎更有效率。目前我確實已經設置了單個關聯表。回答你的問題,我意識到真的不需要這種解決方案。我正在尋找的那種設置會使用更多的內存,雖然對嗎? –

+1

我現在甚至沒有意見的開始。我不認爲有一種做多態的習慣,但我肯定會明天試一試。很好的問題。 Upvoted!編輯:它可能會給你的問題,但我不知道答案:http://stackoverflow.com/questions/6964678/habtm-polymorphic-relationship – Damien

回答

1

是的,從你的描述來看,你無法在標籤上加上可標記的列,因爲它們可以有多個可標記的東西,反之亦然。你提到了HABT,但是就我所知,你不能做任何像has_and_belongs_to,:polymorphic => true的東西。

create_table :object_tags, :id => false do |t| 
    t.integer :tag_id 
    t.integer :tagable_id 
    t.string :tagable_type 
end 

您的其他表不需要object_tags,標記或可標記的列。

class Tag < ActiveRecord::Base 
    has_many :object_tags 
end 

class ObjectTag < ActiveRecord::Base 
    belongs_to :tagable, :polymorphic => true 
    belongs_to :tag 
end 

class Topic < ActiveRecord::Base 
    has_many :object_tags, :as => :tagable 
    has_many :tags, :through => :object_tags 
end