gpt4 book ai didi

ruby-on-rails - Rails has_many through for has_many with multiple models

转载 作者:搜寻专家 更新时间:2023-10-30 20:02:29 34 4
gpt4 key购买 nike

模拟以下情况的最佳方法是什么:

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

我希望能够做到

 @story.words 

获取通过台词或短语链接到故事的所有单词的列表...

这可能吗?

最佳答案

试试这个:

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

现在

story.words # returns line and phrase words
story.words.limit(5)

关于ruby-on-rails - Rails has_many through for has_many with multiple models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11193615/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com