【发布时间】:2015-10-04 04:13:50
【问题描述】:
我的dashboard_helper.rb 中有一个辅助方法,如下所示:
def show_number_of_comments(node)
if node.comments_count == 1
"#{node.comments_count} Comment"
else
"#{node.comments_count} Comments"
end
end
在我的常规dashboard#index 视图中,我这样称呼它:
<h4 class="card-comments-title"><%= show_number_of_comments(node) %></h4>
但我想在添加新评论时通过 AJAX 更新呈现的元素,所以在我的comment#create.js.erb 中,我想引用那个辅助方法,但是当我尝试这个时,它不起作用:
$('#<%= @card_id %> .card-comments-title').html('<%= show_number_of_comments(@node) %>');
但是当我这样做时,它会起作用:
$('#<%= @card_id %> .card-comments-title').html('<%= @comment_count %> Comments');
后者的问题是它不能处理复数。
解决这个问题的最佳方法是什么?
编辑 1
当我说它不起作用时,我的意思是:
NoMethodError at /nodes/5/comments
==================================
> undefined method `show_number_of_comments' for #<#<Class:0x007fbd3715e5b8>:0x007fbd3715d4d8>
app/views/comments/create.js.erb, line 5
----------------------------------------
另外,@node 对象在我的Comments#Create 中声明如下:
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
当我如上所述通过binding.pry 停止执行并尝试执行@node 时,我得到了我期望的值:
[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>
编辑 2
有时它只是失败了。它不会向控制台或我的服务器日志输出任何错误,它只是将.card-comments-title 替换为空白值。
【问题讨论】:
-
纯 JS 方法为您提供了脱离表示的逻辑解耦,您尝试过了吗?
-
“它不起作用”到底是什么意思?您是否收到未定义的方法错误?
-
在 HTML 视图中,使用
node调用辅助方法,在 JS 中使用@node调用它。
标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4