Using will_paginate with multiple models (Rails)

前端 未结 4 476
生来不讨喜
生来不讨喜 2020-12-28 11:34

Pretty sure that I\'m missing something really simple here:

I\'m trying to display a series of pages that contain instances of two different models - Profiles and Gr

4条回答
  •  误落风尘
    2020-12-28 11:51

    in my last project i stuck into a problem, i had to paginate multiple models with single pagination in my search functionality. it should work in a way that the first model should appear first when the results of the first model a second model should continue the results and the third and so on as one single search feed, just like facebook feeds. this is the function i created to do this functionality

    def multi_paginate(models, page, per_page)
    
      WillPaginate::Collection.create(page, per_page) do |pager|
    
        # set total entries
        pager.total_entries = 0
        counts = [0]
        offsets = []
        for model in models
              pager.total_entries += model.count
              counts << model.count
              offset = pager.offset-(offsets[-1] || 0)
              offset = offset>model.count ? model.count : offset 
              offsets << (offset<0 ? 0 : offset)
        end
    
        result = []
        for i in 0...models.count
              result += models[i].limit(pager.per_page-result.length).offset(offsets[i]).to_a
        end
    
        pager.replace(result)
      end
    
    end
    

    try it and let me know if you have any problem with it, i also posted it as an issue to will_paginate repository, if everyone confirmed that it works correctly i'll fork and commit it to the library. https://github.com/mislav/will_paginate/issues/351

提交回复
热议问题