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 id
s 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?
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