0

I have three models: Question, User and Qrecord. A Qrecord stores how many times the User has answered the Question correctly (in the column :answered) and when it was last answered (in the column :last_answered).

So, a Question has_many Qrecords and a User has_many Qrecords. A Qrecord belongs_to :user and :question.

Qrecord Model

id :integer not null, primary key user_id :integer question_id :integer answered :integer last_answered :datetime 

For an array of questions, how do I return the one in which :last_answered was the longest time ago?

1 Answer 1

1

Assuming that the array of questions is questions and the user record user:

user.qrecords.where(question_id: questions.pluck(:id)).order(:last_answered).last.question 
Sign up to request clarification or add additional context in comments.

3 Comments

Nearly right. It also needs the user_id for the qrecord. If you edit it to make the where condition where(question_id: questions.pluck(:id), user_id: user)..., I will mark it as correct.
In that case you can use user.qrecords.where.... I updated the answer.
BTW: Accepting the answer would be very kind.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.