I have a helper method in my dashboard_helper.rb
that looks like this:
def show_number_of_comments(node)
if node.comments_count == 1
"#{node.comments_count} Comment"
else
"#{node.comments_count} Comments"
end
end
In my regular dashboard#index
view, I call it like this:
<h4 class="card-comments-title"><%= show_number_of_comments(node) %></h4>
But I would like to update that rendered element via AJAX whenever a new comment is added, so in my comment#create.js.erb
, I would like to reference that helper method but when I try this, it doesn't work:
$('#<%= @card_id %> .card-comments-title').html('<%= show_number_of_comments(@node) %>');
But when I do this, it works:
$('#<%= @card_id %> .card-comments-title').html('<%= @comment_count %> Comments');
The issue with the latter is that it doesn't handle pluralization.
What's the best way to approach this?
Edit 1
When I say it doesn't work, this is what I mean:
NoMethodError at /nodes/5/comments
==================================
> undefined method `show_number_of_comments' for #<#<Class:0x007fbd3715e5b8>:0x007fbd3715d4d8>
app/views/comments/create.js.erb, line 5
----------------------------------------
Also, the @node
object is declared in my Comments#Create
like this:
def create
@node = Node.find(params[:node_id])
@comment = current_user.comments.new(comment_params)
@comment.node = @node
@card_id = params[:card_id]
@comment_count = @node.comments_count + 1
current_user.events.create(action: "commented", eventable: @comment)
binding.pry
respond_to do |format|
if @comment.save and @node.save
format.js
else
format.js
end
end
end
When I halt execution via binding.pry
as above, and I try to do @node
, I get the value I expect:
[1] pry(#<CommentsController>)> @node
=> #<Node id: 5, name: "Reverse Crunches", family_tree_id: 1, user_id: 1, media_id: 5, media_type: "Video", created_at: "2015-07-25 05:49:51", updated_at: "2015-07-25 21:05:34", circa: nil, is_comment: nil, cached_votes_total: 0, cached_votes_score: 0, cached_votes_up: 0, cached_votes_down: 0, cached_weighted_score: 0, cached_weighted_total: 0, cached_weighted_average: 0.0, cached_user_tag_list: nil, cached_num_user_tags: 0, cached_tagged_user_names: [], comments_count: 3>
Edit 2
Sometimes it just fails. It doesn't output any error to either the console or my server log, it just replaces the .card-comments-title
with a blank value.