2

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 ??

asked Dec 19, 2012 at 11:09

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

one more details I use Hstor on my database :
her is the code : <%= @users.collect{|item| item.details['name'] }
did you try to apply .to_json to it? you show unchanged code from your initial question
1
var tab = <%= @users.collect{|item| item.names }.to_s.html_safe %>;
answered Dec 19, 2012 at 11:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.