【问题标题】:Searchkick pagination, limit and offset issues, railsSearchkick 分页、限制和偏移问题、rails
【发布时间】:2020-11-17 01:06:38
【问题描述】:

我想在第一行显示最后 3 个外观,然后我想显示所有其他外观,但不显示 3 个最后外观。

这是我的代码

def index
    query = params[:query].presence || "*"
    conditions = {}
    conditions[:available] = true
    conditions[:look_tags] = params[:look_tags] if params[:look_tags].present?
    @last_3_looks = Look.search query, where: conditions, order: { created_at: :desc }, limit: 3
    @looks = Look.search query, where: conditions, order: { created_at: :desc }, page: params[:page], per_page: 8
end

问题是如果我像下面这样设置偏移量,我每页都有相同的 8 次查看,请问如何处理?

@looks = Look.search query, where: conditions, order: { created_at: :desc }, page: params[:page], per_page: 8, offset: 3
end

【问题讨论】:

    标签: ruby-on-rails elasticsearch pagination kaminari searchkick


    【解决方案1】:

    只需从@looks 中排除前 3 个结果(检查第 6 行)

    query = params[:query].presence || "*"
    conditions = {}
    conditions[:available] = true
    conditions[:look_tags] = params[:look_tags] if params[:look_tags].present?
    @last_3_looks = Look.search query, where: conditions, order: { created_at: :desc }, limit: 3
    conditions[:id] = { not: @last_3_looks.results.collect(&:id) }
    @looks = Look.search query, where: conditions, order: { created_at: :desc }, page: params[:page], per_page: 8
    

    【讨论】:

      【解决方案2】:

      好像你想计算偏移量,比如:

        page = params[:page].to_i
        per_page = 8
        starting_offset = 3
        offset = starting_offset + ((page - 1) * per_page)
      
        @looks = Look.search query, where: conditions, order: { created_at: :desc }, page: page, per_page: per_page, offset: offset
      

      但您也可以考虑使用kaminari gem,它会为您进行计算。 好像是 Searchkick allows that

      另外,请参阅answers

      【讨论】:

      • 谢谢,我试过你的代码,但它确实有效,我已经在使用 kaminari。 Wen 在 searchick 上使用偏移量,它删除了最后 3 个外观,但是当我更改页面时,它一次又一次地显示每页相同的外观....我只想要 Look.all 上的偏移量 => 只需删除 3 个外观然后显示每页 8 个外观
      • 你能告诉我什么不起作用吗?有什么错误?另外,您的页数是否从 1 开始? (或者可能是 0?)
      • 好吧,我试图解释最简单的(对不起我的英语): - 在 Look#index 上,仅在第 1 页我想显示 3 个最新的外观,由“@last_3_looks”(工作正常)-然后我不想在“@looks”中显示这 3 个外观,并且想用 kaminari 显示每页 8 个外观,问题是如果我在查询中输入 offset: 3,它们不再在这里,但如果我转到下一页它总是显示相同的 8 个外观,如果我移动它,我仍然在“@looks”中看到最后 3 个外观,但分页工作正常......非常挣扎......
      猜你喜欢
      • 1970-01-01
      • 2012-11-21
      • 2017-04-14
      • 2016-03-16
      • 1970-01-01
      • 2022-11-03
      • 2014-09-20
      • 2014-08-26
      • 2012-02-01
      相关资源
      最近更新 更多