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?
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)
@BKSpurgeon You can do this entirely in the DB using something like
User.where("engagement < ?", current_user.engagement).count + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With