我有一个帮助方法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
Run Code Online (Sandbox Code Playgroud)
在我的常规dashboard#index视图中,我称之为:
<h4 class="card-comments-title"><%= show_number_of_comments(node) %></h4>
Run Code Online (Sandbox Code Playgroud)
但是我想在添加新注释时通过AJAX更新渲染的元素,所以在我看来comment#create.js.erb,我想引用那个帮助方法,但是当我尝试这个时,它不起作用:
$('#<%= @card_id %> .card-comments-title').html('<%= show_number_of_comments(@node) %>');
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,它的工作原理是:
$('#<%= @card_id %> .card-comments-title').html('<%= @comment_count %> Comments');
Run Code Online (Sandbox Code Playgroud)
后者的问题是它不处理多元化.
什么是最好的方法来解决这个问题?
编辑1
当我说它不起作用时,这就是我的意思:
NoMethodError at /nodes/5/comments
==================================
> undefined method `show_number_of_comments' for #<#<Class:0x007fbd3715e5b8>:0x007fbd3715d4d8>
app/views/comments/create.js.erb, line 5
----------------------------------------
Run Code Online (Sandbox Code Playgroud)
此外,该@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 …Run Code Online (Sandbox Code Playgroud) 如何包含资源管道执行上下文可访问的Rails视图助手?
一个示例用例是使用form_tag帮助器方法为表单生成标记,并使其可用于Javascript模板(如handlebars,jst等).
我使用handlebar_assets gem,但这也适用于任何erb或haml模板.
这就是我在我的erb.js文件中所拥有的....但它不起作用:
1 //Update with a message
2 $('#follow-update').html("<%= follow_button(@question) %>")
Run Code Online (Sandbox Code Playgroud)
follow_button是一个帮手:
20 def follow_button(resource)
21
22 type = resource.class.name
23 follow_status = current_user.following?(resource)
24
25 verb = "Follow" if follow_status == false
26 verb = "Unfollow" if follow_status == true
27
28 content_tag(:div, :class => "follow-button") do
29 link_to "#{verb} this #{type} ", follow_path(:followed_type => type,
30 :followed_id => resource.id,
31 :follow_verb => verb),
32 :class => "button",
33 :remote => true
34 end
35 end
36 end
Run Code Online (Sandbox Code Playgroud)
帮助程序独立工作正常,但我希望它更新我的按钮.也许有一种方法可以在不更换整个助手的情况下更新文本?