I'm consuming an external API, and I would like to create some sort of pagination for the index action. The API returns 15 elements (which is the limit I specified in the HttParty query hash) and I can add the "page" option too. For starters, I tried putting an incremental in the view and passing it as a param, and it works but only for one page (ex. from page 1 to 2) and then it just reloads the second page. How could I achieve my goal? I know there are some gems out there but I would like to learn it myself. Here's the code:
controller
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
view
<h1 >Listing all properties</h1>
<div >
<%@response["content"].each do |property|%>
<div >
<div >
<%if property["title_image_thumb"]%>
<%=image_tag property["title_image_thumb"]%>
<%else%>
<p ><i ></i> No image</p>
<%end%>
</div>
<div >
<p ><%=property["public_id"]%></p>
<p ><%=property["title"]%></p>
<p ><%=property["property_type"]%></p>
<p ><i ></i> <%=property["location"]%></p>
</div>
<div >
<%=link_to 'Go to property', "properties/#{property["public_id"]}"%>
</div>
</div>
<%end%>
</div>
<div >
<%i = 1%>
<%=link_to 'Next page', root_path(:page => i =1)>
</div>
PD: My goal is to add two buttons, one for the previous page and one for the next page
CodePudding user response:
You need to use the page you are currently showing when rendering the view:
<div >
<%=link_to 'Next page', root_path(:page => @current_page 1)>
</div>
To achieve this you need to set in the controller:
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