My application has the concept of registration questions and answers
class RegistrationQuestion < ApplicationRecord
has_many :registration_answers, dependent: :destroy
# RegistrationQuestions that are 'original' questions are the questions
# configured to join as a full member, they have a null original_id field.
# However we also support 'one time events'. When created those events get a copy of the full
# registration questions so that users can have different questions for one time events compared to full membership
belongs_to :original, class_name: "RegistrationQuestion", optional: true
has_many :derived_questions, class_name: "RegistrationQuestion", foreign_key: 'original_id'
end
In order to give returning users suggested answers, I'd like to retrieve the most recent answer for any related question. Here's where I'm getting tripped up:
class RegistrationAnswer < ApplicationRecord
belongs_to :registration_question
# Simplified. I can get the related question ids, need help getting distinct answers
def self.related_answers_for(profile, question_ids)
recent_related_answer_ids = RegistrationAnswer.joins(:registration_question)
.where(profile: profile, registration_question_id: related_question_ids)
.order(updated_at: :desc)
.select('registration_questions.original_id', :updated_at, :id)
.group('registration_questions.original_id')
.map { |ra| ra.id }
RegistrationAnswer.where(id: related_answer_ids)
end
end
I'm trying to get the most recent answer for any related registration question. Related registration questions are ones with the same original_id set.
However this sql throws a "PG::GroupingError: ERROR" telling me I need to put both updated_at and id in the group clause. However, when I add those two it is no longer grouping them as I want, since it's returning the group distinct based on the registration answer id. What I really want is the most recent answer, grouped by the registration_question.original id only.