Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROR passing array as parameter

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.

like image 807
nilkash Avatar asked Jul 23 '15 13:07

nilkash


People also ask

How do you pass an array as a parameter in Ruby?

It is also possible to pass an array as an argument to a method. For example, you might want a method that calculates the average of all the numbers in an array. Your main program might look like this: data = [3.5, 4.7, 8.6, 2.9] average = get_average(data) puts "The average is #{average}."

Can you pass an array as a parameter in Javascript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.

How to pass array with pointer?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().


2 Answers

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.

like image 60
RAJ Avatar answered Oct 14 '22 09:10

RAJ


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

like image 36
Sudhir Avatar answered Oct 14 '22 10:10

Sudhir