[英]Rails has_many through for has_many with multiple models
What would be the best way to model the following situation: 对以下情况进行建模的最佳方法是什么:
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
I want to be able to do 我想能够做
@story.words
to get list of all words that are linked to a story either via lines or via phrases... 通过行或短语获取链接到故事的所有单词的列表...
Is that possible? 那可能吗?
Try this: 尝试这个:
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
Now 现在
story.words # returns line and phrase words
story.words.limit(5)
You can remove the 2 has_many :words, :through => XXX
relations from the Story
class, and define a method words
instead : 您可以从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.