【问题标题】:为外部 API Rails 手动构建分页
【发布时间】:2022-01-22 07:17:10
【问题描述】:

我正在使用一个外部 API,我想为索引操作创建某种分页。 API 返回 15 个元素(这是我在 HttParty 查询哈希中指定的限制),我也可以添加“页面”选项。对于初学者,我尝试在视图中放置一个增量并将其作为参数传递,它只适用于一页(例如从第 1 页到第 2 页),然后它只是重新加载第二页。我怎样才能实现我的目标?我知道那里有一些宝石,但我想自己学习。代码如下:

控制器

class PropertiesController < ApplicationController
  BASE_URL='https://api.stagingeb.com/v1/properties'
  HEADERS = { 
    "X-Authorization"  => ENV['API_KEY']
  }

  def index
    page = params[:page]
    query = {
      "limit" => "15",
      "page" => page || 1
    }
    request = HTTParty.get(BASE_URL, :query => query, :headers => HEADERS)
    @response = JSON.parse(request.body)
  end

  def show
    request = HTTParty.get(BASE_URL + "/#{params[:id]}", :headers => HEADERS)
    @response = JSON.parse(request.body)
  end
  
end

查看

<h1 class="index-heading">Listing all properties</h1>
<div class="main-wrapper">
  <%@response["content"].each do |property|%>
    <div class="property-card">
      <div class="image">
        <%if property["title_image_thumb"]%>
          <%=image_tag property["title_image_thumb"]%>
        <%else%>
          <p class="noimage"><i class="fas fa-exclamation-triangle"></i> No image</p>
        <%end%>
      </div>
      <div class="card-text">
        <p class="public-id"><%=property["public_id"]%></p>
        <p class="title"><%=property["title"]%></p>
        <p class="type"><%=property["property_type"]%></p>
        <p class="type"><i class="fas fa-map-marker-alt"></i> <%=property["location"]%></p>
      </div>
      <div class="property-link">
        <%=link_to 'Go to property', "properties/#{property["public_id"]}"%>
      </div>
    </div>
  <%end%>
</div>
<div class="pagination">
  <%i = 1%>
  <%=link_to 'Next page', root_path(:page => i+=1)>
</div>

PD:我的目标是添加两个按钮,一个用于上一页,一个用于下一页

【问题讨论】:

    标签: ruby-on-rails ruby api http


    【解决方案1】:

    渲染视图时需要使用当前显示的页面:

    <div class="pagination">
      <%=link_to 'Next page', root_path(:page => @current_page + 1)>
    </div>
    

    要实现这一点,您需要在控制器中设置:

      def index
        @current_page = [1, params[:page].to_i].max
        query = {
          "limit" => "15",
          "page" => @current_page
        }
        request = HTTParty.get(BASE_URL, :query => query, :headers => HEADERS)
        @response = JSON.parse(request.body)
      end
    

    【讨论】:

      猜你喜欢
      • 2015-09-02
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 2018-06-26
      • 1970-01-01
      • 2015-05-28
      • 1970-01-01
      相关资源
      最近更新 更多