简体   繁体   中英

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 :

def words 
  ([] << lines.collect {|line| line.words} << phrases.collect {|phrase| phrase.words}).flatten
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM