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?
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 %>');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With