Rails has_many通过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
我希望能够做到
@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)
您可以从Story
类中删除2个has_many :words, :through => XXX
关系,并定义一个方法words
:
def words ([] << lines.collect {|line| line.words} << phrases.collect {|phrase| phrase.words}).flatten end
- Ruby on rails – 将text_field的表单值传递给不同控制器中的操作参数
- 使用rails缓存时使用rails处理redis maxmemory情况
- Rails SQL查询构建器…或ActiveRecord查询构建器
- 控制器根据前一页重定向到不同的路径
- Gem / Bundler加载错误:无法激活…已激活
- Rails ActiveModelSerializer将两个相同类型模型的列表组合成一个序列化响应,具有不同的名称
- Rails 3:未知的validation器:’PresenceValidator’(ArgumentError)
- Rails .where()查询不起作用
- 使用Foreman重新启动单个进程