Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find position in active record object

I have a league table that i create with:

 QuizuserAnswer.all(:include =>:user, :select => 'user_id, SUM(answer) AS points', :group =>'user_id', :order=>'points DESC'

This returns an object like this:

 => [#<QuizuserAnswer user_id: 340>, #<QuizuserAnswer user_id: 348>]

Now i want to find the league table position of one specific user. Is there a clean way? or do i have to loop through al columns?

like image 875
flyte321 Avatar asked Sep 03 '13 12:09

flyte321


People also ask

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What is ORM in ROR?

ORM is Object Relational Mapper. It means you don't have to manually call the database yourself; the ORM handles it for you. Ruby on Rails uses one called ActiveRecord, and it's a really good one. ORM allows you to do things such as: User.

What is Arel_table?

arel_table end. The Arel::Table object acts like a hash which contains each column on the table. The columns given by Arel are a type of Node , which means it has several methods available on it to construct queries. You can find a list of most of the methods available on Node s in the file predications.

What is Activemodel?

A toolkit for building modeling frameworks like Active Record. Rich support for attributes, callbacks, validations, serialization, internationalization, and testing.


1 Answers

From a very little i got your question i think you want something like following

answers = QuizuserAnswer.all(:include =>:user, :select => 'user_id, SUM(answer) AS points', :group =>'user_id', :order=>'points DESC')
user_id = 348
answers.map(&:user_id).index(user_id) #This will return 1

i.e It will return the position of the answer given by the user among the answer's list

like image 109
Salil Avatar answered Oct 21 '22 07:10

Salil