简体   繁体   English

将SQL查询转换为Ruby on Rails

[英]Translate SQL query to Ruby on Rails

I need to convert a relatively simple query to display a total quiz average for a given user in a table set up in Rails/HAML. 我需要转换一个相对简单的查询,以在Rails / HAML中设置的表中显示给定用户的总测验平均值。 We have users take quizzes, record the scores, and display the average per quiz. 我们有用户参加测验,记录分数并显示每个测验的平均值。 We now want to total average of all quizzes. 现在,我们要求所有测验的总平均值。 Easy: 简单:

SELECT (ROUND(AVG(`score`*100), 1)) FROM `quiz_results` WHERE `user_id`=$user

The results need to display in a table cell that is already set up, but I cannot figure this out. 结果需要显示在已经设置的表格单元中,但是我无法弄清楚。

Perhaps this line will help. 也许这条线会有所帮助。 It's pre-existing code that calculates the average of a particular quiz for that user: 它是预先存在的代码,用于为该用户计算特定测验的平均值:

%td.separate="#{(((lesson.quiz_results.average('score', :conditions => "user_id = #{@user.id}")) * 100).to_i)}%"

I have Rails 2.3.x. 我有Rails2.3.x。

Well, as i can see now - all you need is to remove particular quiz restriction, which is imposed by association usage lesson.quiz_results - instead of it just use model class, which is most likely QuizResult . 好吧,正如我现在所看到的-您所需要的只是删除由关联用法lesson.quiz_results施加的特定测验限制-而不是仅使用模型类,这很可能是QuizResult

And, also, there is tiny bug in your existing code - .to_i will rounding down, you should use .round . 而且,您现有的代码中也有一个小错误.to_i将四舍五入,您应该使用.round See the difference: 看到不同:

irb(main):002:0> 1.6.to_i
=> 1
irb(main):003:0> 1.6.round
=> 2

So, full code should be: 因此,完整的代码应为:

(QuizResult.average('score', :conditions => "user_id = #{@user.id}") * 100).round

(I also removed some unnecessary brackets) (我还删除了一些不必要的括号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM