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!