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

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 %>;
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

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 %>;

Comments

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.