Stp*_*tpn 2 database ruby-on-rails relational-database 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
Run Code Online (Sandbox Code Playgroud)
我希望能够做到
@story.words
Run Code Online (Sandbox Code Playgroud)
获取通过线条或短语链接到故事的所有单词的列表...
那可能吗?
试试这个:
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
Run Code Online (Sandbox Code Playgroud)
现在
story.words # returns line and phrase words
story.words.limit(5)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2065 次 |
| 最近记录: |