Fetch objects upon pagination, rather than beforehand? (Rails + Kaminari)

爱⌒轻易说出口 提交于 2019-12-25 05:12:20

问题


So I have a search controller that returns a array of Object IDs (in this case 'Users').

Since the search results array can contain hundreds of IDs, I'd rather fetch the actual Objects themselves only when I need to send them to the view. In short, I want to use pagination to fetch the Objects themselves beforehand for each chunk of IDs (i.e. 1..10, 11..20, etc), rather than have the view logic fetch the Objects. I have no idea how to accomplish this.

My controller code

users = [1,3,456,23423,234,23...]
#somehow have the pagination get the Objects from DB for each page
@persons = Kaminari.paginate_array(users).page(params[:page]).per(10)

View

- @persons.each do |person| #I WANT TO HAVE THE FULL WRITER OBJECT BY NOW
  = person.name             # instead of doing a 'User.find(person.id)' in the view

Any ideas?

Thanks in advance!


回答1:


put a page number parameter in the url. Then if you want to display 10 per page and say the user clicks page three, subtract page number by one page (10) and add one giving you 21. this is your start for the database query. and limit to 10 results




回答2:


I'm an idiot. You can just map or collect a new array based on the @persons array



来源:https://stackoverflow.com/questions/10126316/fetch-objects-upon-pagination-rather-than-beforehand-rails-kaminari

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