Skip to content
Advertisement

Ordering records by an association presence

Lets say I have an instructions table which is associated to a surveys table through survey_instructions join table.

What I need to achieve is to fetch all instruction records, but ordered by an association presence with a given survey.

So instructions associated with a given survey will go first, and then all other instructions which have no association with this survey.

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

Could this be achieved by chaining active record queries somehow? Would appreciate any thoughts on this

Advertisement

Answer

Yes you can achieve this by ActiveRecord query. Try this:

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")

Happy coding 🙂

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement