Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

<h2>posts show</h2>

(etc...)

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

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

(etc...)

</div>

<%= yield %>

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

</html>

But I'm getting 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-<%[email protected]%>").html('<%=escape_javascript @post.votes.count %>');
4:   </script>
5: <% end %>

Any suggestions to fix this?

like image 568
alexchenco Avatar asked Feb 06 '12 03:02

alexchenco


2 Answers

escape_javascript calls gsub on whatever you pass it, which doesn't make sense for a number. You can either not call escape_javascript or give it a String instead:

$("post-<%[email protected]%>").html('<%=escape_javascript @post.votes.count.to_s %>');
like image 170
Andrew Marshall Avatar answered Oct 11 '22 11:10

Andrew Marshall


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

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

Notice that you don't need to wrap the <%= %> expression in quotes since to_json will do that for you when necessary.

like image 34
Brandan Avatar answered Oct 11 '22 11:10

Brandan