1

I have a controller designed to perform simple CRUD operations. The model of my data has an attribute called start_date. What should I do in order to make my API return a JSON response with only the entries with a start_date value between two dates that I can specify in the body of the request?

Jagdeep Singh
  • 4,880
  • 2
  • 17
  • 22
  • 1
    Possible duplicate of [Rails ActiveRecord date between](https://stackoverflow.com/questions/2381718/rails-activerecord-date-between) – Vishal Aug 22 '18 at 12:54
  • could you post your controller code with the action that is hit by the request? – John Baker Aug 22 '18 at 13:01

1 Answers1

1

This is more like a generic question about filtering that could be applied to any API request.

If you make a GET request for an endpoint like example.com/model you would have to pass some parameters, in that case, 2 dates in the URL. So it would be something like this:

example.com/model?start_date=12.12.2017&end_date=15.12.2017

This example is super simple of course. You can pass those dates in different ways like a timestamp or ISO format. that is up to you.

On the backend side, you have to fetch those parameters from the request and perform a query on your model. something like this:

def index
  start_date = params[:start_date]
  end_date = params[:end_date]
  # Make sure to parse the params and transform in a date object
  result = Model.where('start_date < ? AND start_date > ?', end_date, start_date)
  respond_to do |format|
    format.json { render json: result }
  end  
end
Bruno Paulino
  • 5,611
  • 1
  • 41
  • 40