Warm tip: This article is reproduced from serverfault.com, please click

How to query a list of objects from a Rails API?

发布于 2020-11-30 16:53:30

I am trying to query a list of objects from a Rails API. That is, let's say I'd like to get the instances with id 2, 4 and 7 from a certain model.

My closest guess so far has been passing a comma-separated string of ids to a regular resource/:id route, then I split the param, built an array from it and passed it to a where call.

It works - however, I feel like this is not a clean way of doing what I am aiming to do.

So I'm asking you if there's a Rails way of handling this.

How should the URL look like? How do I read the passed values from the controller?

Questioner
zcserei
Viewed
0
Dmitry Barskov 2020-12-01 01:40:33

I think that it should be a filter on index path accepting ids param.

So URL should look like

/resource?ids[]=2&ids[]=4&ids[]=7

And you can find those resources with

def index
  if params[:ids].blank?
    @resources = Resource.all
  else
    @resources = Resource.find(params[:ids])
  end
end