2013-02-15 124 views
0

我有一个红宝石函数创建一个哈希的实例变量,我有麻烦accesing它的JavaScript内的值。嵌入红宝石的JavaScript,红宝石不承认

这是我的控制器:

class TransferController < ApplicationController 
    def index 
     require 'json' 
     #@transfers = Transfer.select("transfer_id,section_id,sum(net) as net").group("transfer_id,section_id").having("sum(net) <> ?",0).order("transfer_id ASC") 
     @transfers = Transfer.select("section_id,section_name,sum(net) as net").group("section_id,section_name").order("section_id ASC") 

     h = Hash.new() 
     a = [] 

     @transfers.each do |section| 
      h["name"] = section.section_name 
      h["size"] = section.net 
      a.insert(h) 
     end 

     @sectionhash = Hash.new() 
     @sectionhash["name"] = "stringush" 
     @sectionhash["children"] = a 


    end 
end 

,这是我的看法:

<h1><%= @sectionhash["name"] %></h1> 

<script src="http://d3js.org/d3.v3.min.js"></script> 
<script type="text/javascript"> 
var x = <%= @sectionhash["name"] %>; 
alert(x); 
</script> 

的reuslt我得到的是,显示我的散列内的值,但JavaScript并没有什么。我甚至试图在Ruby代码的分配之前加入一个警报,它工作。所以它不符合嵌入式ruby。 我见过这个论坛的人回答说我写的嵌入式行是合法的。 任何想法,为什么这不工作?

回答

5

你仍然需要遵守正常的Javascript synax规则。 var x = <%= @sectionhash["name"] %>;将打印:var x = stringush;由于没有变量称为stringush而无效。你需要引用的JS字符串,像这样:

var x = '<%= @sectionhash["name"] %>';

这将打印:var x = 'stringush';这是你想要的。

2

我认为你要找的是x是字符串"stringush"。为此,改变你的JavaScript来:

<script type="text/javascript"> 
    var x = '<%= @sectionhash["name"] %>'; 
    alert(x); 
</script> 

您需要报价在那里和JavaScript将是var x = stringush;和因为没有所谓的stringush变量x将是不确定的。