How to query for a list of associated records using Rails 4 + PostgreSQL?
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 "Recen
·
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.
已为社区贡献19912条内容
所有评论(0)