Working on a learning management system. NOT a RoR person. Have the line of HAML to generate an average score based on quizzes taken:
="#{(QuizResult.average('score', :conditions => "user_id = #{@user.id}") * 100).round}%"
The quiz_results table has columns for used_id and score.
However, if there are no records in the quiz_results table, the page doesn’t render. I want to check if any scores exist for that user id, and if so, to show the average. If none exist, I want to display “No quizzes taken.” here’s what I have:
19: %td
20: -if QuizResult('score', :conditions => "user_id = #{@user.id}").exists?
21: ="#{(QuizResult.average('score', :conditions => "user_id = #{@user.id}") * 100).round}%"
22: -else
23: %em No quizzes taken
I get the following error:
“ActionView::TemplateError (undefined method `QuizResult’ for #ActionView::Base:0x7028c7f5cb88>) on line #20 of app/views/manage_users/show_all_users.haml:”
I’ve been struggling all day with this. Any suggestions? Thanks in advance, from an RoR noob.
I am guessing that
QuizResultis a model class. If that is the case then you cannot use it as a method to look up an instance.There are various ways that you can look up an object by some condition, for example:
To check for null (or nil as its referred to in Ruby) you can use the
nil?method that Ruby itself provides or the Rails convenience methodpresent?which returns true unless the object is nil, an empty string or empty collection.