【问题标题】:Ordering records by an association presence按关联存在排序记录
【发布时间】:2019-04-12 11:04:49
【问题描述】:

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

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

因此,与给定调查相关的说明将首先执行,然后是与此调查无关的所有其他说明。

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】:

    是的,您可以通过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")
    

    编码愉快:)

    【讨论】:

    • 不幸的是没有帮助,因为它只是把所有没有调查的指令放在最后。但我需要的是使用给定的调查 id,首先获取给定调查的所有相关说明,然后是与该调查无关的所有说明。他们可能与其他调查有任何关联
    • @A.Chile 我已经编辑了答案。希望这篇文章对您有所帮助。
    • 刚刚试了一下,它产生了ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "survey_instructions" :(
    • 在您的 Rails 控制台上,运行 SurveyInstruction.last 并在此处共享日志。
    • SurveyInstruction Load (9.3ms) SELECT "survey_instructions".* FROM "survey_instructions" ORDER BY "survey_instructions"."id" DESC LIMIT $1 [["LIMIT", 1]]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2019-11-26
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多