通过关联存在排序记录

问题描述 投票:0回答:1

假设我有一张instructions表,它通过surveys连接表与survey_instructions表相关联。

我需要实现的是获取所有指令记录,但是通过给定调查的关联存在来排序。

因此,与给定调查相关的指令将首先出现,然后是与此调查无关的所有其他指令。

class Instruction < ApplicationRecord
  has_many :survey_instructions, dependent: :destroy
  has_many :surveys, through: :survey_instructions
and
class Survey < ApplicationRecord
  has_many :survey_instructions, dependent: :destroy
  has_many :instructions, through: :survey_instructions
and
class SurveyInstruction < ApplicationRecord
  belongs_to :survey
  belongs_to :instruction
and

这可以通过以某种方式链接活动记录查询来实现吗?不胜感激任何想法

sql ruby-on-rails postgresql activerecord ruby-on-rails-5
1个回答
0
投票

是的,您可以通过ActiveRecord查询来实现此目的。试试这个:

survay_id = 10
@instructions = Instruction.includes(:survey_instructions).order("(CASE WHEN survey_instructions.survay_id = #{survay_id} THEN 1 ELSE 2 END) ASC NULLS LAST")

快乐编码:)

© www.soinside.com 2019 - 2024. All rights reserved.