Rails has_many through for has_many with multiple models

三世轮回 提交于 2019-12-03 21:39:36
Harish Shetty

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 :

def words 
  ([] << lines.collect {|line| line.words} << phrases.collect {|phrase| phrase.words}).flatten
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!