2014-04-01 154 views
0

我有三個型號:問題用戶Qrecord。 A Qrecord存儲了用戶已回答問題正確(在列中:已回答)和上次回覆時間(在列中:last_answered)多少次。活動記錄聯接查詢

所以,一個問題has_many Qrecords和一個用戶has_many Qrecords。 Qrecord belongs_to:用戶和:問題。

Qrecord型號

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

有關問題的數組,我怎麼回的一個,其中:last_answered是時間最長的前?

回答

1

假設的問題陣列是questions和用戶記錄user

user.qrecords.where(question_id: questions.pluck(:id)).order(:last_answered).last.question 
+0

近右側。它還需要qrecord的user_id。如果您編輯它以使where條件在哪裏(question_id:questions.pluck(:id),user_id:user)...,我會將其標記爲正確。 – Finnjon

+0

並且非常感謝! – Finnjon

+0

在這種情況下,您可以使用'user.qrecords.where ...'。我更新了答案。 – wintermeyer