使用will_paginate多个模型(滑轨)(Using will_paginate with m

2019-06-25 06:23发布

敢肯定,我的思念很简单的东西在这里:

我想展示了一系列含有两种不同型号的情况下页 - 配置文件和组。 我需要他们通过他们的name属性排序。 我可以选择所有实例的每个模型,然后进行排序和分页他们,但这种感觉草率和低效。

我使用mislav-will_paginate,并想知道是否有实现这一目标的任何更好的办法? 就像是:

[Profile, Group].paginate(...)

将是理想!

Answer 1:

好问题,我遇到了同样的问题了几次。 每一次,我结束了它的基于SQL工会写我自己的SQL查询(它正常工作与SQLite和MySQL的)。 然后,您可以使用将通过将结果分页( http://www.pathf.com/blogs/2008/06/how-to-use-will_paginate-with-non-activerecord-collectionarray/ )。 不要忘了执行查询计数所有行。

一些代码行(未测试)

my_query = "(select posts.title from posts) UNIONS (select profiles.name from profiles)"
total_entries = ActiveRecord::Base.connection.execute("select count(*) as count from (#{my_query})").first['count'].to_i

results = ActiveRecord::Base.connection.select_rows("select * from (#{my_query}) limit #{limit} offset #{offset}")

难道overkilled? 也许但你查询的最小数量和结果是一致的。

希望能帮助到你。

注意:如果你从一个http PARAM获得偏移值,你应该使用sanitize_sql_for_conditions(即:SQL注入....)



Answer 2:

你可以亲近做这样的事情:

@profiles, @groups = [Profile, Group].map do |clazz|
  clazz.paginate(:page => params[clazz.to_s.downcase + "_page"], :order => 'name')
end

然后,将使用分页页面参数profile_pagegroup_page 。 你可以得到will_paginate使用,使用正确的页面视图电话:

<%= will_paginate @profiles, :page_param => 'profile_page' %>
....
<%= will_paginate @groups, :page_param => 'group_page' %>

不过,我不知道有过建立一个巨大的好处@groups@profiles独立。



Answer 3:

在我的最后一个项目我坚持了一个问题,我不得不分页多个模型,在我的搜索功能单一分页。 它应该在工作方式是第一种模式应首先出现在第一种模式的结果的第二个模型应该继续的结果,第三等为一个单一的搜索饲料,就像Facebook的饲料。 这是我创建做这个功能的作用

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

试试吧,让我知道,如果你有任何问题的话,我还张贴作为一个问题will_paginate库,如果每个人都证实它可以正常工作,我会叉,它提交到库中。 https://github.com/mislav/will_paginate/issues/351



Answer 4:

您是否尝试过用自己的paginators显示两个不同的结果,并通过AJAX更新呢? 这不正是你想要的,但结果是类似的。



文章来源: Using will_paginate with multiple models (Rails)