Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails params to array

I am sending a list of checkbox selected from PHP file to our Rails API server. All checked items' ID's will be sent in json format (campaign_ids in json_encode from PHP):

I got a URL being passed to our API like this

 Started PUT "/campaigns/function.json?campaign_ids=["6","7"]&user_id=0090000007"

I need to get the campaign_ids ["6","7"] and process it like any other array using array.each do || end

How can I convert this to an array so I can use array.each?

The following sample code can achieve it but I think there could be a better way?

campaign_ids = params[:campaign_ids].to_s          # [\"6\",\"7\"]
campaign_ids = campaign_ids.gsub(/[^0-9,]/,'')     # 6,7

if campaign_ids.size.to_i > 0                      # 3 ??
   campaign_ids.split(",").each do |campaign_id|   
      ...
   end
end
like image 672
jck Avatar asked Mar 28 '17 06:03

jck


2 Answers

The correct format of the URL should've been campaign_ids[]=6&campaign_ids[]=7. That would automatically yield an array of [6, 7] when you do params[:campaign_ids].

But assuming you can't change the format of the incorrect parameters, you can still get it via JSON.parse(params[:campaign_ids])

like image 59
Ho Man Avatar answered Sep 19 '22 17:09

Ho Man


Try this

campaign_ids = JSON.parse(params[:campaign_ids])

You get params[:campaign_ids] as a string. So, you will have to parse that json string to get array elements.

like image 23
Sajin Avatar answered Sep 18 '22 17:09

Sajin