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?
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
来源:https://stackoverflow.com/questions/11193615/rails-has-many-through-for-has-many-with-multiple-models