haffane hatim
haffane hatim

Reputation: 474

Array between Rails and JavaScript

I'm working on a ROR application and i need to get an array from my database and use it on JS , so i did this

var tab = <%= @users.collect{|item| item.names }%>;

But when i try to use may Tab i get this error :

SyntaxError: syntax error   
var tab = [&quot;123456789&quot;, &quot;fDF125847&quot;, &quot;124578&q

i think that I need to cast the & quot; to " but i dont know how ??

Upvotes: 2

Views: 98

Answers (3)

Misha Reyzlin
Misha Reyzlin

Reputation: 13896

You should use JSON for this. Something among the lines

var tab = <%= @users.collect{|item| item.names }.to_json %>;

Or in case your collection doesn't have to_json method, you could use ActiveSupport::JSON and its encode method.

UPD. Also I'd recommend to read How to Securely Bootstrap JSON in a Rails View

Upvotes: 2

Bruno Campos
Bruno Campos

Reputation: 2188

var tab = <%= @users.collect{|item| item.names }.to_s.html_safe %>;

Upvotes: 1

davidb
davidb

Reputation: 8954

Instead of

var tab = <%= @users.collect{|item| item.names }%>;

you should write

var tab = <%= @users.collect{|item| item.names }.to_json.html_safe %>;

Upvotes: 5

Related Questions