Search code examples
ruby-on-railsjsonrails-api

Limit number of json results - Rails API


I am creating Rails API and when I do get request to mywebsite.com/posts/all it shows me all the post data. I am trying to do mywebsite.com/posts/all?limit=20 to show 20 results or some other number. What is the way to achieve it with rails?


Solution

  • Limit will not work, each time if u call this method it will return only last 20 records, Best way to achieve this result using pagination, here you can limit number record passing when each request is hitting

    You can use gem will_paginate

    In controller

    @posts = Post.paginate(:page => params[:page], :per_page => 20)
    

    In the view

    <%= will_paginate @posts %>
    

    For info about will_paginate https://github.com/mislav/will_paginate/blob/master/README.md

    If u r using API pass params ass below

    GET /v1/posts?page=1&per_page=10  
    

    Change value in controller

    @posts = Post.paginate(page: params[:page], per_page: params[:per_page])