[英]Rails has_many through for has_many with multiple models
對以下情況進行建模的最佳方法是什么:
Word
belongs_to :wordable, :polymorphic => true
Phrase
has_many :words, :as => :workable
belongs_to :story
Line
has_many :words, :as => :wordable
belongs_to :story
Story
has_many :lines
has_many :phrases
has_many :words, :through => :phrases
has_many :words, :through => :lines
我想能夠做
@story.words
通過行或短語獲取鏈接到故事的所有單詞的列表...
那可能嗎?
嘗試這個:
class Story
has_many :lines
has_many :phrases
def words(reload=false)
@words = nil if reload
@words ||= Word.where("(wordable_type = ? AND wordable_id IN (?)) OR
(wordable_type = ? AND wordable_id IN (?))",
"Phrase", phrase_ids, "Line", line_ids)
end
end
現在
story.words # returns line and phrase words
story.words.limit(5)
您可以從Story
類中刪除2個has_many :words, :through => XXX
關系,然后定義一個方法words
:
def words
([] << lines.collect {|line| line.words} << phrases.collect {|phrase| phrase.words}).flatten
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.