在RubyonRails中创建一个用于Javascript的变量
可能重复: 有没有办法在RubyonRails视图中创建一种变量,以便以后在javascript标记中使用 我想这样做:在RubyonRails中创建一个用于Javascript的变量,javascript,ruby-on-rails-3,Javascript,Ruby On Rails 3,可能重复: 有没有办法在RubyonRails视图中创建一种变量,以便以后在javascript标记中使用 我想这样做: <p> <% test=Build.where("result = 1").count(:result) %> of the builds succeeded. </p> <%= javascript_tag do %> console.log(test); <%
<p>
<% test=Build.where("result = 1").count(:result) %> of the builds succeeded.
</p>
<%= javascript_tag do %>
console.log(test);
<% end %>
有办法吗?这是行不通的。
提前谢谢 您可以使用 因为你想把它显示为一个字符串
console.log('<%= Build.where("result = 1").count(:result) %>');
您可以使用访问erb中的任何ruby变量 因为你想把它显示为一个字符串
console.log('<%= Build.where("result = 1").count(:result) %>');
如果可能的话,我会将逻辑移到控制器中,再看一下gon gem: 编辑:我看错了你的问题
# Controller
@test = Build.where("result = 1").count(:result)
# View
<%= javascript_tag do %>
console.log(<%= @test %>);
<% end %>
如果可能的话,我会将逻辑移到控制器中,再看一下gon gem: 编辑:我看错了你的问题
# Controller
@test = Build.where("result = 1").count(:result)
# View
<%= javascript_tag do %>
console.log(<%= @test %>);
<% end %>
console.log;变量位于eruby上下文中,而不是JS。一定要引用它,除非它是一个数值。哦,谢谢,对不起,我以为我已经试过了!我想这能解决我更大的问题!console.log;变量位于eruby上下文中,而不是JS。一定要引用它,除非它是一个数值。哦,谢谢,对不起,我以为我已经试过了!我想这能解决我更大的问题!