Answer a question

I have the following models:

Question.rb
  has_many :answers
end

class Answer.rb
  belongs_to :question
end

What I want to do is get the most recent 10 Answers, and show a list of "Recently Answered Questions"

If I query for Answer.last(10), that provides the answers, How somehow translate the recent answers into a list of @questions I can render?

Answers

show a list of "Recently Answered Questions"

You're approaching it from the wrong angle, you should be querying questions table:

@questions = Question.joins(:answers)
                     .group('questions.id, answers.created_at')
                     .order('answers.created_at DESC')
                     .limit(10)

This will fire a single db query and instantly return you 10 recent questions with answers.

Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容