我试图找到一种聪明的方法来获取一些记录。
我有这些课程:
class Question < ActiveRecord::Base
belongs_to :section
has_many :answers
has_many :quiz_questions
has_many :quizzes, through: :quiz_questions
has_many :question_stats
end
class User < ActiveRecord::Base
has_many :quizzes, dependent: :destroy
has_one :user_profile
has_many :questions, through: :quizzes
has_many :question_stats
end
class Section < ActiveRecord::Base
has_many :questions
has_many :quizzes
end
class QuestionStat < ActiveRecord::Base
belongs_to :user
belongs_to :question
end
如果我查询
current_user.question_stats
我收到了我的对象
=> [#<QuestionStat id: 1, user_id: 2, question_id: 2, errors_count: 0, done_count: 0, done: false>,
#<QuestionStat id: 6, user_id: 2, question_id: 39, errors_count: 0, done_count: 0, done: false>,
#<QuestionStat id: 7, user_id: 2, question_id: 102, errors_count: 0, done_count: 0, done: false>,
#<QuestionStat id: 8, user_id: 2, question_id: 96, errors_count: 0, done_count: 0, done: false>,
#<QuestionStat id: 9, user_id: 2, question_id: 46, errors_count: 0, done_count: 0, done: false>,
#<QuestionStat id: 10, user_id: 2, question_id: 119, errors_count: 0, done_count: 0, done: false>,
我需要对部分的统计数据进行分组,因此我知道每个部分用户已经回答了多少问题以及他做了多少错误。
Question_id belongs_to属于section_to的问题。
我还尝试以另一种方式继续,从current_user.questions
开始如果我查询
current_user.questions
我获得了用户回答的所有问题。
<Question id: 94, quiz_type: "base", image: nil, text: "Com'è chiamato l'insieme degli organi con i quali ...", section_id: 1>,
#<Question id: 68, quiz_type: "base", image: nil, text: "Come viene denominata la parte di calpestio più ba...", section_id: 1>,
#<Question id: 111, quiz_type: "base", image: nil, text: "Un'elica destrorsa:", section_id: 1>,
#<Question id: 103, quiz_type: "base", image: nil, text: "Si ha cavitazione quando:", section_id: 1>
当然
current_user.questions.first.questions_stats.first
返回与单个用户相关的具体问题的统计信息。
答案 0 :(得分:0)
我建议在问题统计中加入section_id
,以便您可以直接执行
QuestionStat.where(section: 1, user_id: current_user.id)
你拥有当前的关联/表格/列的方式,按行业划分问题统计数据的查询在我能够察觉的情况下会非常混乱和低效。