Reputation: 53
I want to be able to return User.all
with current_user
as the first result, and the rest sorted alphabetically by user.name
.
What's the "Rails" way to do this? I think it's to convert the ActiveRecord_Relation to an array and then use a combo of .insert
and .delete_at
to move the target User from its current position to the front. Would I want to create a helper method for that? Or is there a completely different approach?
Thanks!
Upvotes: 1
Views: 927
Reputation: 2957
In one query:
users = User.where("id != ?", current_user.id).all.insert(0, User.find(current_user.id))
However, please remember that it's almost always a bad idea to build your site around User.all
queries... after 10,000+ users your app will grind to a halt. Wherever you are doing this query you should paginate the results.
Upvotes: 1
Reputation: 4433
Not the most "railsy" way, but this should work:
users = User.all.append(User.find(current_user.id))
users = (users & users).reverse!
Upvotes: 1