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!

2
  • 1
    stackoverflow.com/questions/3061273/… this seems to answer your problem, the second answer Commented Aug 4, 2014 at 15:43
  • Are you creating an API or using an API? Commented Aug 4, 2014 at 15:45

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

@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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.