2012-06-06 10 views
7

Ho un allineamento di Ruby come questo nel mio controller:Dall'array Ruby all'array JS in Rails- 'quote'?

@location_list = [ 
     ['Mushrooms', 3], 
     ['Onions', 1], 
     ['Olives', 1], 
     ['Zucchini', 1], 
     ['Pepperoni', 2] 
     ] 

E sto Facendo in questo modo, a mio avviso:

location_list = "<%= @location_list.to_json %>"; 

Ma se faccio alert (location_list), ottengo:

[[&quot;Mushrooms&quot;,3],[&quot;Onions&quot;,1],[&quot;Olives&quot;,1],[&quot;Zucchini&quot;,1],[&quot;Pepperoni&quot;,2]] 

Come posso ottenere l'oggetto corrispondente, senza quelle & quot?

risposta

25

Prova:

<%= raw @location_list.as_json %> 

Utilizzando to_json finirà rendering di una stringa, con doppi apici embedded, e avrebbe bisogno di essere JS-sfuggito. E sarebbe una stringa, non una matrice.

+0

L'ho provato. Il problema principale è che quando eseguo raw o html_safe vedo "Identificatore imprevisto" (nella console) quando provo ad usare quella var. Anche se vedo la fonte, posso vedere questo: var location_list = "[[" Funghi ", 3], [" Cipolle ", 1], [" Olive ", 1], [" Zucchini ", 1], [ "Pepperoni", 2]] "; console.log (location_list); - Cosa può succedere? –

+0

@HommerSmith Come stai provando ad usarlo? Inoltre, se è effettivamente quotato in quel modo, è una stringa - non una matrice; hai provato 'as_json'? –

+0

Sto solo provando a mostrarlo nella console ... Fondamentalmente voglio passare un array da Ruby a JS ... Se cambio l'array di ruby ​​è come questo: @location_list = [1,3,4] - - Non capisco quell'errore È solo quando ci sono stringhe all'interno della matrice che ottengo "identificatore imprevisto" nella mia console di Chrome. –

-1

questo ha funzionato per me:

<%= @location_list.to_s.gsub(''', '') %> 

Fondamentalmente utilizzare .to_s per convertire l'intero array in una stringa, quindi utilizzare .gsub(''','') per rimuovere le virgolette sostituendoli con niente.

+0

perché il downvote? – andrewcockerham