Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
Daniel Bonnell Avatar asked Nov 21 '16 21:11

Daniel Bonnell


2 Answers

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)
like image 141
usha Avatar answered Sep 25 '22 08:09

usha


@BKSpurgeon You can do this entirely in the DB using something like

User.where("engagement < ?", current_user.engagement).count + 1
like image 29
montrealmike Avatar answered Sep 25 '22 08:09

montrealmike