Passing an ROR array as a parameter

I'm trying to pass an array as a parameter to my controller method, but it doesn't work for me. I tried it in the following ways:

http://localhost:3000/med?med_ids=[2,1]

      

I tried as much as his job for me. I just want to know a good solution

http://localhost:3000/manufacturer/1/medicines?medicine_id[]=2&medicine_id[]=1

      

internal controller:

@val = params[:medicine_id]

      

but I want to do it as an array.

Help is needed. Thank.

+3


source to share


3 answers


If you are trying to send a parameter like [1,2], then in your controller you will get "[1,2]",

and you need to parse to get in the original array, for example: JSON.parse "[1,2]"



ans: [1,2] and Array class

+1


source


You cannot get an array from a query string like this:

?med_ids=[2,1]

      

If you want to pass an array in a query string, you need to pass it as follows (as you mentioned in the question):



?medicine_id[]=2&medicine_id[]=1

      

As an answer to your question: 2nd way is absolutely good way and right way. Go with him.

+3


source


You can further customize the controllers to parse the delimited array:

?medicine_ids=1,2

      

controller:

medicine_ids = params[:medicine_ids].split(',')

      

0


source







All Articles