[英]Rails get list of records in batches with custom order
I have to display a list of users and information about them.我必须显示用户列表和有关他们的信息。 But since there are many users in my database, the SQL is really slow.但是由于我的数据库中有很多用户,所以 SQL真的很慢。 Now I would like to display the users in batches of, say, 100 and then reveal/load more as you click "View more".现在我想分批显示用户,比如 100 个,然后在单击“查看更多”时显示/加载更多。
How would I go about doing that in practice?我将如何 go 在实践中这样做?
[Note: I have a custom order that should be preserved, so the methods in the Rails Documentation don't really help me] [注意:我有一个应该保留的自定义顺序,所以 Rails 文档中的方法并没有真正帮助我]
You can use the property called limit and offset .您可以使用名为limit和offset的属性。 with this you can limit to tell the number of records to be fetched , and use offset to tell the number of records to skip before starting to return the records .有了这个,您可以限制告知要获取的记录数,并使用偏移量告知在开始返回记录之前要跳过的记录数。
example:例子:
User.limit(3) # this returns first three records
It will generate following sql query.它将生成以下 sql 查询。
"SELECT `users`.* FROM `users` LIMIT 3"
As offset is not mentioned in above query so it will return first three records.由于上述查询中未提及偏移量,因此它将返回前三个记录。
User.limit(5).offset(30)
#returns 5 records starting from 31th so you will get the records from 31 to 35
It will generate following sql query.它将生成以下 sql 查询。
"SELECT `users`.* FROM `users` LIMIT 5 OFFSET 30"
You're effectively looking for pagination.您正在有效地寻找分页。 The most commonly used gem for this is kaminari .最常用的宝石是kaminari 。
You give a default page size to a model, in your case users, and then call您为 model(在您的情况下为用户)提供默认页面大小,然后调用
User.page(1)
to access the first page of results.访问结果的第一页。 In your controller this will generally look something like:在您的 controller 中,这通常看起来像:
@users = User.order(:name).page params[:page]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.