Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

get values from ruby to javascript


Am new to ruby on rails.I want to get the values from ruby to java script.Here is the code iam using.

What i want is i want to create a data variable in json format with speed and time values from ruby.Above static values are used

 <table border='1' align='center' class="table table-striped" >                         
  <tr>                          
    <th>Id</th>     
    <th>Speed</th>
    <th>Time</th>
  </tr>
<%  @properties.each do |c| %> 
  <tr>
    <td><%= c.device_id %></td>
    <td><%= c.speed %></td>  
    <td><%= c.time %></td>  
  </tr>
<% end %>                   
</table>
<p><div align='center'>Available Time vs Speed Details are listed below</div> </p>
<div id="bar-demo" align="center">
<script type="text/javascript">
var data = "[[{ 'time': '1', 'speed': '0' }, { 'time': '2', 'speed': '1' }]]
</script></div>

Inside javascript can i use ruby code like this?

<script type="text/javascript">
<%  @properties.each do |c| %> 
    var data = "[[{ 'time': 'c.time', 'speed': 'c.speed' }]]
<% end %>        
</script>

Also i need to get data like this(in comma separated form)

var data = "[[{ 'time': '1', 'speed': '0' }, { 'time': '2', 'speed': '1' }]]

How it is possible.


Solution

  • Try this, (not tested)

    <script type="text/javascript">
      var data = <%=[@properties.map {|c| {time:c.time, speed:c.speed}}].to_json%>
    </script>