简体   繁体   中英

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. Now I would like to display the users in batches of, say, 100 and then reveal/load more as you click "View more".

How would I go about doing that in practice?

[Note: I have a custom order that should be preserved, so the methods in the Rails Documentation don't really help me]

You can use the property called limit and 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.

"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.

"SELECT  `users`.* FROM `users` LIMIT 5 OFFSET 30"

You're effectively looking for pagination. The most commonly used gem for this is kaminari .

You give a default page size to a model, in your case users, and then call

User.page(1)

to access the first page of results. In your controller this will generally look something like:

@users = User.order(:name).page params[:page]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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