简体   繁体   English

Rails API子集响应

[英]Rails API subsetting response

I have a controller designed to perform simple CRUD operations. 我有一个设计用于执行简单CRUD操作的控制器。 The model of my data has an attribute called start_date . 我的数据模型具有一个名为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? 为了使我的API返回一个JSON响应,该响应只包含可以在请求正文中指定的两个日期之间的start_date值的条目,我该怎么做?

This is more like a generic question about filtering that could be applied to any API request. 这更像是有关可应用于任何API请求的过滤的通用问题。

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. 如果您对诸如example.com/model类的端点发出GET请求,则必须传递一些参数,在这种情况下,URL中应包含2个日期。 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. 您可以通过不同的方式传递这些日期,例如时间戳或ISO格式。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM