简体   繁体   中英

Iterate through a hash from the Rails controller in js

In my rails controller i have made an hash which looks like this:

@data = {

 term => {        
   node_id => {
    :name,
    :matchcode,
    :credits,
    :parts => [{
      :mp_id,
      :matchcode,
      :nr,
      :selected
    }]

}}

Now i want to iterate in js through this hash to get the keys and values. At first I need the term i tried to get it with something like:

for(var s in '#{@data}') {
   console.log(s);
}

But i seems like I did something wrong it's the first time i use rails..

Passing data from the server side ruby controller to client side javascript code is not that simple. Firstly, javascript has no idea about ruby variables, the above is simply string '#{data}' which evaluates to itself.

There are couple of ways of passing such a data:

Firstly, you can set an html attribute on DOM element server side and then read it in your javascript. This might be simplest solution when passing a string or a number, for a hash however it is quite messy as you need to convert it into a form understandable by javascipt - into JSON. Even though it is very simple to do, it just adds extra complexity and is just dirty.

Second option is a gon gem. It provides you with an object you can assign data to in your controller. Then it handles all the transformations and you can access all the data in your javascript:

# controller
gon.my_data = {a: 1}

#js
gon.myData  #=> {"a": 1}

This solution is very simple, however it still feels a little bit dirty.

Final, cleanest and more complex solution is to use AJAX - your javascript makes a request to your server to receive the data. Might be an overkill in many situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM