1

I'm using the jQuery plugin jQuery-Tokenizing-Autocomplete in a rails application with a has_many association.

I need to save the values to the database, but to do that I need it to be a string, not an array. So the result should equal "1","2","3". Hope this clarifies.

The javascript used to generate this array:

$.TokenList.ParseValue = function (value, settings) {
  var result = [];
  $.each(value, function(i, node) {
    if (node) {
      result.push(node.id);
    }
  });
  return result;  
};

3 Answers 3

1

for array to string in javascript you can do it like this.

var str = (['1', '2', '3']).join(","); // will result to 1,2,3

similar syntax works for ruby code

['1', '2', '3']).join(",") # will return 1,2,3
Sign up to request clarification or add additional context in comments.

Comments

0

The default separator for join is the comma, so remove the '","' argument. You are specifying a separator of "," so the double quotes must be escaped in the result string, hence the backslashes.

5 Comments

That leaves me with "hotel_ids"=>["1,2,3"] and not the ["1","2","3"] that rails require.
Why not split the array into an array of separate strings back in the controller? Something like hotel_ids[0].split(',')
$ irb >> a = ["1,2,3"] => ["1,2,3"] >> a[0].split(',') => ["1", "2", "3"] >>
Great idea, would you happen to know the best way to make the array a string? the split method makes it an array. So the end result is [["1","2","3"]]. Thanks!
If you have an array or arrays, use the flatten method. [["1","2","3"]].flatten yields ["1","2","3"]
0
var string = '"' + array.join('","') + '"'; // "1","2","3"

1 Comment

That works, except for the it getting escaped: "1\",\"2\",\"3"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.