简体   繁体   English

在ActiveRecord_Relation结果中移动项目?

[英]Moving items in ActiveRecord_Relation result?

I want to be able to return User.all with current_user as the first result, and the rest sorted alphabetically by user.name . 我希望能够以current_user作为第一个结果返回User.all ,其余的按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. 我认为这是将ActiveRecord_Relation转换为数组,然后使用.insert.delete_at的组合将目标User从其当前位置移到最前面。 Would I want to create a helper method for that? 我想为此创建一个辅助方法吗? Or is there a completely different approach? 还是有完全不同的方法?

Thanks! 谢谢!

Not the most "railsy" way, but this should work: 不是最“卑鄙的”方式,但这应该可以工作:

users  = User.all.append(User.find(current_user.id))
users = (users & users).reverse!

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. 但是,请记住,围绕User.all查询构建您的网站几乎总是一个坏主意……在10,000个以上的用户之后,您的应用程序将停止运行。 Wherever you are doing this query you should paginate the results. 无论您在哪里进行此查询,都应对结果进行分页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM