Rails has_many through for has_many with multiple models

核能气质少年 提交于 2019-12-21 05:51:22

问题


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?


回答1:


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) 



回答2:


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


来源:https://stackoverflow.com/questions/11193615/rails-has-many-through-for-has-many-with-multiple-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!