首页 > 解决方案 > 如何在 Rails 中包含查询中的多个订单

问题描述

我有两个模型:QuestionAnswer. 问题 - 答案关系是1-n

我的问题和答案都有order属性,现在我需要按顺序列出问题及其答案。

某事喜欢:

Question.includes(:answers).order(questions: {order: :asc}, answers: {order: :asc})

任何帮助都非常受欢迎!

标签: ruby-on-rails

解决方案


has_many您可以在模型中指定订单。

# app/models/question.rb
# This will order answers by date, you presumably want something else
has_many :answers, -> { order(date: :desc) }

推荐阅读