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
                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])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With