Ruby ActiveRecord getting a range up to last entry?

混江龙づ霸主 提交于 2019-12-24 16:42:55

问题


Suppose I have 100 entries in my database, my mobile application has an infinite listview which queries the database for the entries.

The application displays items in batches of 15, once a user reaches the end of the 15 items, the application will query for the next 15 items. This means that there will be a remained of 10 items to make a total 100 items.

I have tried looking at some of the ActiveRecord's method such as find:

# Find the clients with primary keys 1 and 10.
clients = Client.find([var, var+14]) # var integer is provided by GET request.
# => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">]

However, it is noted that The find method will raise an ActiveRecord::RecordNotFound exception unless a matching record is found for all of the supplied primary keys.

How then would I go about fetching the last 10 items to show on screen? Also, is it possible to get ActiveRecord to return a value when there are no items in range so I can display an all items shown message?


回答1:


Client.offset(15 * iteration).first(15)

is what I would recommend here. Then iteration should be 0 for the first 15, 1 the second time you refresh your list. Of course you can adjust the way you compute your offset.

You might want to specify a order though, to keep it consistent.




回答2:


Client.limit(15).offset(var).order(:id)

This is what I would suggest as to the best of my knowledge shouldn't throw you any errors



来源:https://stackoverflow.com/questions/51155282/ruby-activerecord-getting-a-range-up-to-last-entry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!