Getting the undefined `gsub 'method for 6: Fixnum (Rails) in a view using jQuery + ERB?

I am trying to add some jQuery + ERB to a specific view:

views / posts / show.html.erb (at the top of the file):

<% content_for :javascript do %>
  <script type="text/javascript">
    $(".post-<%=@post.id%> h3").prepend('<%=escape_javascript @post.votes.count %>');
  </script>
<% end %>

<h2>posts show</h2>

(etc...)

<div class="post-<%=@post.id%>">
  <h3>votes</h3><br />
  <%= link_to "Vote Up", vote_up_path(@post), :remote => true %><br />
</div>

views / layouts / application.html.erb (at the bottom of the file):

(etc...)

</div>

<%= yield %>

<%= yield :javascript %>
</body>

</html>

But I get the following error:

undefined method `gsub' for 6:Fixnum
Extracted source (around line #3):

1: <% content_for :javascript do %>
2:   <script type="text/javascript">
3:     $("post-<%=@post.id%>").html('<%=escape_javascript @post.votes.count %>');
4:   </script>
5: <% end %>

Any suggestions for fixing this issue?

+5
source share
2 answers

escape_javascriptcalls gsubon everything you pass it on, which makes no sense to the number. You can either not call escape_javascriptor pass a string instead:

$("post-<%=@post.id%>").html('<%=escape_javascript @post.votes.count.to_s %>');
+14
source

Since @post.votes.count(presumably) is just an integer value, you can simply use to_json:

$(".post-<%= @post.id %> h3").prepend(<%= @post.votes.count.to_json %>);

, <%= %> , to_json , .

+3

All Articles