5

I am trying pass array as parameter to my controller method but it's not working for me. I tried it in following ways:

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

I tried in following way as well and its working for me. I just want to know any good solution

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

inside controller:

@val = params[:medicine_id]

values are coming but I want to make it as array.

Need some help. Thank you.

6
  • 1
    What are you getting in params[:medicine_id] Commented Jul 23, 2015 at 13:23
  • You could JSON encode your array and then parse it from your controller Commented Jul 23, 2015 at 13:24
  • I am getting as string Commented Jul 23, 2015 at 13:24
  • Try: ?medicine_id%5B%5D=2&medicine_id%5B%5D=1 Commented Jul 23, 2015 at 13:30
  • If I am reading question correctly, ?medicine_id[]=2&medicine_id[]=1 is working for you. And this is the correct way to pass array in query string Commented Jul 23, 2015 at 13:31

3 Answers 3

6

You cannot get array from query string like this:

?med_ids=[2,1]

If you want to pass an array in query string, you need to pass it as follow (as you have mentioned in question):

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

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

ans: [1,2] and class Array

Comments

0

You can optionally build your controllers to parse a delimited array:

?medicine_ids=1,2

controller:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.