2010-09-07 39 views
0

隨着Rails 3出來我想知道是否有一種新的方式做has_many:通過與多態模型的關聯?如果不是什麼最好這樣做呢?有許多通過關聯多態性錯誤

這裏就是我與

class Page < ActiveRecord::Base 
end 

class Text < ActiveRecord::Base 
end 

class Picture < ActiveRecord::Base 
end 

的工作文字和圖片是屬於一個或多個頁面的內容 - 每一頁都有一個或多個內容元素(文本或圖片)。我希望能夠做到這一點:

page.content => ["text item 1", "text item 2", "picture 1"] 
picture.pages => ["page 3", "page 7"] 

正如我上面提到我使用Rails 3.任何想法的工作?

回答

1

我會用HMT和STI:

class Page < ActiveRecord::Base 
    has_many :assets, :through => :page_components 

    def content 
    self.assets 
    end 
end 

class PageComponent < ActiveRecord::Base 
    # could also use HABTM 
    belongs_to :page 
    belongs_to :asset 
end 

class Asset < ActiveRecord::Base 
    has_many :pages, :through => :page_components 
end 

class Text < Asset 
    # inherits .pages association method from Asset 
end 

class Picture < Asset 
    # so does this. 
end 

# class Video < Asset... 
1

有一個在Rails 3中並沒有什麼區別2

class Page < ActiveRecord::Base 
    belongs_to :text # foreign key - text_id 
    belongs_to :picture  # foreign key - picture_id 
end 
class Text < ActiveRecord::Base 
    has_many : pictures 
    has_many :pictures, :through => :pages 
end 
class Picture < ActiveRecord::Base 
    has_many :assignments 
    has_many :texts, :through => :pages 
end 

第二個想法

你最後的評論讓我想,你也許有一噸CONTENT_TYPES的,或moreso,該CONTENT_TYPES可能能夠生成客戶端。

下面是一個替代方案,爲什麼不製作一個模型,頁面 - 並使其具有反映其content_type的屬性。然後你就可以與他們的關係像這樣..

@show_texts = Page.find(:all).select{ |p| p.text != nil }.collect{|p| p.id}.inspect 

等等等等..只是一個想法。說實話,我會嘗試重構上面的代碼以獲得SQL友好的版本,因爲這是用來打擊數據庫的很多方法。

+0

這只是一個一對多。我需要一個多對多的。我還應該注意,在上面的示例中,我只有2種內容類型,但我可以有更多... – LDK 2010-09-07 00:48:39

+0

最好忽略多態的方式,並按照上面的建議進行操作。然而,當我添加更多的內容類型時,Page將會有很多「belongs_to」語句...... – LDK 2010-09-07 01:22:41

+0

我不確定我是否理解你的大圖。模型本身是否會生成客戶端?你有多少'content_types'?這至少可以爲您提供很好的服務。我將在上面更新一個替代方案。 – Trip 2010-09-07 01:42:32