You may not love this answer, but I'd recommend sticking w/ SQL. You should be able to use an if statement in your sql to just make users w/o answers set to 0. I dealt with a similar issue a while ago and found the sql was so much more preformant.
Rails 3.1 Join average
-
30-06-2022 - |
Question
I have a user_questions table(UserQuestion model) and user_answers table(UserAnswer model) and they have data in this format.
user_questions table:
+------+-----------------------------------------------------+---------------------+
| id | question | created_at |
+------+-----------------------------------------------------+---------------------+
| 1 | Is question asker is a fool? | 2011-03-12 03:23:44 |
| 2 | have we got an answer yet? | 2011-03-12 03:24:06 |
+------+-----------------------------------------------------+---------------------+
user_answers table:
+------+-------+------------------+---------------------+
| id | value | user_question_id | created_at |
+------+-------+------------------+---------------------+
| 1 | Yes he is! | 1 | 2011-03-12 04:23:44 |
| 2 | OC he is! | 1 | 2011-03-12 05:23:44 |
| 3 | yup he is! | 1 | 2011-03-12 05:23:44 |
+------+-------+------------------+---------------------+
Now i need to find the average age of questions i.e avg(user_question.created_at - min(user_answers.created_at))
With the above data: Since user_question(1) got its first answer in exactly 1 hour so his age is : 1 hours
since user_question(2) has not yet got any answer its age is (DateTime.now - user_question.created_at(lets say its 1000 hours)).
result_output = (1 + 1000)/2
I am pretty familiar with mysql sum, avg, min, max operations. But unfortunately struggling very badly here to get the final solution with rails join operator.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow