David
David

Reputation: 85

Use Javascript to generate Rails Text Array

I am attempting to write some JavaScript that allows a user to enter a zip code one at a time and build up an array that will be submitted to a Rails app.

Here are the relevant pieces:

Controller.rb - Params

    {:zipcodes => []} 

Schema.rb

    t.text     "zipcodes",       default: [],              array: true

html.erb The javascript updates the value of a hidden element

    <%= f.hidden_field :zipcodes, id:"zipcodes-hidden-tag", name:"provider[zipcodes]" %>

js.erb file

    //Adding a zipcode
     var array = []; 
     $("#addZipcode").click(

    function addZipcode() {

        x = $("#newZipcode").val();  // gets the zipcode entered by the user
        array.push(x);
        $("#zipcode_div").text(array);  // updates a div so the user can see the data entered
        $("#newZipcode").val("");  //clear the zipcode box after submitting
        $("#zipcodes-hidden-tag").val("[" + '"",' + '"' + array.join('","') + '"' + "]");  //puts the brackets, empty quote block, and quotes around the elements and updates the hidden field value
    }); //Adding a zipcode  

This is how it looks in the Rails console when it is successful (using a multi-select field):

    "provider"=>{"zipcodes"=>["", "90210", "90211", "90212"],

When using the Javascript generated array, I can see the following value getting passed to Rails which is the correct formatting

    ["","90210","90211","90212"] 

But in the Rails console, it's coming through like this:

   "provider"=>{"zipcodes"=>"[\"\",\"90210\",\"90211\",\"90212\"]"

And Rails is stating

    Unpermitted parameter: zipcodes

I feel like there are two problems at play here. An extra set of quotes are getting added to the beginning and end of the brackets:

    "[  ...   ]"    

And the double quotes are getting converted into literals with the back slashes.

Any thoughts on what I need to change to get this to work?

Thanks!

Upvotes: 1

Views: 46

Answers (2)

ahmacleod
ahmacleod

Reputation: 4310

The output from the console,

"provider"=>{"zipcodes"=>"[\"\",\"90210\",\"90211\",\"90212\"]"

is exactly what you should expect. Your javascript code encodes the array as a string and submits it through a hidden field, so params[:provider][:zipcodes] is a string in your controller. In order to assign it to your model, you'll need to do something like

provider.zipcodes = JSON.parse(params[:provider][:zipcodes])

The Unpermitted parameter: zipcodes message is most likely because you are mass-assigning to your model without whitelisting or removing the zipcodes key from your params hash.

Edit:

To get around the strong parameters, try deleting the zipcodes key.

provider.zipcodes = JSON.parse(params[:provider].delete(:zipcodes))

safe_params = params.require(:provider).permit(:any, :other, :fields)
provider.update!(safe_params)

Upvotes: 1

Surya
Surya

Reputation: 15992

Instead of this line:

$("#zipcodes-hidden-tag").val("[" + '"",' + '"' + array.join('","') + '"' + "]");

if you change it to:

$("#zipcodes-hidden-tag").val('"' + array.join('","')); 

then you will have values as: "979794,297942,24444"

Which would make it super easy to convert into an array in your controller:

params[:provider][:zipcodes].split(',') 
#=> ["979794", "297942", "24444"]

Which can be:

params[:provider][:zipcodes] = params[:provider][:zipcodes].split(',')

Upvotes: 0

Related Questions