如何在Rails中包含多个订单

时间:2019-06-30 19:31:35

标签: ruby-on-rails

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

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

像:

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

我们非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我提出了解决方案

@questions = Question
               .includes(:answers)
               .includes(:categories)
               .order('questions.order desc', 'answers.order desc').all

了解更多here