Rails has_many通过has_many与多个模型

模拟以下情况的最佳方法是什么:

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