0

I need to fetch several ids in one GET request like

http://localhost:3000/api/positions/ids

I've tried some ways to do this, but no one worked:

This returned only first object:

http://localhost:3000/api/positions/1,2

this

http://localhost:3000/api/positions?id=1,2

and that

http://localhost:3000/api/positions?id=1&id=2

returned all objects, but first and second.

How can I do it? Thanks!

Pavel
  • 1,934
  • 3
  • 30
  • 49

1 Answers1

2

The syntax for arrays in parameters is id[]=1&id[]=2&id[]=3 but if you have large numbers of ids then this can become quite cumbersome and ugly. I would suggest that you use the parameter id for a single id and a separate parameter ids which takes a hyphen-seperated single string, eg

#get a single resource
/api/positions?id=123

#get a list of resources
/api/positions?ids=123-67-456-1-3-5

Now you can make your controller code something like this:

if params[:id]
  @foos = Foo.find_all_by_id(params[:id])
elsif params[:ids]
  @foos = Foo.find_all_by_id(params[:ids].split("-"))
end
Max Williams
  • 32,435
  • 31
  • 130
  • 197
  • @Max In your code "@foos = Foo.find_all_by_id(params[:ids].split("-"))" the 'Foo' is some database service i guess. Am i correct? Also its upto the 'find_all_by_id' function implementation that it should return the list of resources – Amol Dixit Jan 23 '17 at 14:26
  • Yes, "Foo.find_all_by_id" refers to Rails' implementation of the ActiveRecord pattern, and is equivalent to `"select * from foos where id in (123,456,789)"`. It will return an array of Foo objects, the ones matching the ids in the string. – Max Williams Jan 23 '17 at 17:04