There are many answers to the question.
It is easy to find answers to all questions and order them according to the latest answer:
def self.answered
joins(:answers).order('answers.created_at desc')
end
In the controller, I would do @answered = Question.answered
But this returns duplicate entries if the question was received more than once.
On the other hand, it’s easy to find various questions that have been answered, but only if I’m not trying to sort them by their created_at dates:
def self.answered
joins(:answers).select("DISTINCT questions.title")
end
(Assume that the headings of the questions are considered unique, so this leads to the appearance of all unique entries).
Problem:
This query cannot be sorted by the "created_at" date of the answer because I only selected the question title in my SQL select statement ...
def self.answered
joins(:answers).select("DISTINCT questions.title").order('answers.created_at desc')
end
leads to this error (I use Postgres):
PGError: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
, , "answer.created_at" , DISTINCT.
, , questions.created_at, , :
def self.answered
joins(:answers).select("DISTINCT(questions.title), questions.created_at").order('questions.created_at desc')
end
SQL. ( ) created_at date?
Rails 3 Active Record, SQL - . , - .