[英]getting unique records on the basis of specific associated column - rails active record associations
I have three models. 我有三种模式。
User
, Question
and Attempt
. User
, Question
和Attempt
。
Each User has_many :attempts
, 每个
User has_many :attempts
,
similarly, Question has_many :attempts
同样,
Question has_many :attempts
and Attempt belongs_to User
and Question
和
Attempt belongs_to User
和Question
Required: 需要:
What I want is a method to return a user's last attempt for every question that user has an associated attempt. 我想要的是一种针对用户具有关联尝试的每个问题返回用户的最后尝试的方法。
I mean if a user has attempted q1, q2 and has 3 attempts for each question, then my method should return last attempt of q1 and last attempt of q2. 我的意思是,如果用户尝试了q1,q2并针对每个问题进行了3次尝试,那么我的方法应该返回q1的最后一次尝试和q2的最后一次尝试。
Right now: I have created a method in User
model. 现在:我已经在
User
模型中创建了一个方法。
def last_attempts
return self.attempts.joins(:question).order("questions.id ASC ,attempts.updated_at DESC").select("DISTINCT ON (question_id) *")
end
Error: This method returns duplicate attempts. 错误:此方法返回重复的尝试。 (all attempts for every question of that user).
(针对该用户的每个问题的所有尝试)。 all 3 attempts of q1 and all three attempts of q2
q1的所有3次尝试和q2的所有3次尝试
It looks like you have an unnecessary join in your query. 看起来您的查询中有不必要的联接。
You should be able to do the following: 您应该能够执行以下操作:
def questions_last_attempts
attempts
.select("DISTINCT ON (question_id) *")
.order(:question_id, created_at: :desc)
end
Which should generate the following SQL: 哪个应生成以下SQL:
SELECT DISTINCT ON (question_id) * FROM "attempts" WHERE "attempts"."user_id" = 1 ORDER BY "attempts"."question_id" ASC, "attempts"."created_at" DESC
One way is to add a relationship between User
and Question
through Attempt
. 一种方法是通过
Attempt
在User
和Question
之间添加关系。
Then map the user.questions
ids to select each time the first ordered attempt: 然后映射
user.questions
id以选择每次第一次有序尝试:
class User < ApplicationRecord
has_many :attempts
has_many :questions, through: :attempts
def last_attempts
questions.order(:id).distinct.map do |question|
attempts.where(question_id: question.id).order(updated_at: :desc).first
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.