ACIDSTEALTH ACIDSTEALTH - 16 days ago 8
SQL Question

ActiveRecord find position (index) of record within relation based off value of attribute

I have a collection ActiveRecord

User
objects.
User
has an attribute,
engagement
, which is a float. Assuming
users = User.all.order(engagement: :desc)
returns 1000 records and
current_user
is a
User
object within
users
, I would like to know the position or index
current_user
within
users
without querying the database again or using an enumerator method such as
each_with_index
, which is slow. Is this possible?

Answer

collect the ids and find the index of the current_user.id

index = User.all.order(engagement: :desc).map(&:id).index(current_user.id)

you can just pluck the id to avoid map

index = User.order(engagement: :desc).pluck(:id).index(current_user.id)