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 = ["123456789", "fDF125847", "124578&q
i think that I need to cast the & quot; to " but i dont know how ??
asked Dec 19, 2012 at 11:09
haffane hatim
4745 silver badges30 bronze badges
3 Answers 3
Instead of
var tab = <%= @users.collect{|item| item.names }%>;
you should write
var tab = <%= @users.collect{|item| item.names }.to_json.html_safe %>;
answered Dec 19, 2012 at 11:35
davidb
8,9645 gold badges40 silver badges72 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Dec 19, 2012 at 11:12
Misha Reyzlin
13.9k4 gold badges57 silver badges65 bronze badges
3 Comments
haffane hatim
one more details I use Hstor on my database :
haffane hatim
her is the code : <%= @users.collect{|item| item.details['name'] }
Misha Reyzlin
did you try to apply
.to_json to it? you show unchanged code from your initial questionvar tab = <%= @users.collect{|item| item.names }.to_s.html_safe %>;
answered Dec 19, 2012 at 11:37
Bruno Campos
2,1871 gold badge20 silver badges34 bronze badges
Comments
default