如何从JS ERB中执行辅助方法?

时间:2022-06-23 07:00:22

I have a helper method in my dashboard_helper.rb that looks like this:

我在dashboard_helper函数中有一个helper函数。像这样的rb:

  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:

但是我希望在添加新注释时通过AJAX更新呈现的元素,所以在我的注释#create.js中。嗯,我想引用那个辅助方法,但是当我尝试这个方法时,它不起作用:

$('#<%= @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

编辑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:

另外,@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

When I halt execution via binding.pry as above, and I try to do @node, I get the value I expect:

当我通过绑定停止执行时。如上所述,我尝试做@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>

Edit 2

编辑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.

有时它只是失败。它不会向控制台或我的服务器日志输出任何错误,它只是用一个空值替换.card-comments-title。

6 个解决方案

#1


5  

So I figured out what I wanted to do in my specific case, i.e. pluralize comment count within my JS ERB, but I haven't figured out how to use a helper_method from within my JS ERB - so this answer doesn't really answer this question.

所以我找到了我想要在我的特定情况下做的事情,即在我的JS ERB中使用复数注释计数,但是我还没有找到如何在我的JS ERB中使用helper_method——所以这个答案并没有真正回答这个问题。

However, I am documenting this here in case someone else has a similar issue and my solution helps them.

然而,我在这里记录这些,以防其他人有类似的问题,我的解决方案可以帮助他们。

In my JS ERB, all I did was used the Rails method pluralize. I completely forgot about it until I typed up this question and it works like a charm.

在我的JS ERB中,我所做的一切都是使用Rails方法多元化。我完全忘记了,直到我输入了这个问题,它就像一个魅力。

Here is the code snippet for my create.js.erb:

这是我的create.j .erb的代码片段。

$('#<%= @card_id %> .card-comments-title').html('<%= pluralize(@comment_count, "Comment") %>');

Works like a charm, but this still doesn't answer my question about referencing/using helper methods here.

工作起来像一个魅力,但这仍然没有回答我的问题,关于引用/使用助手方法。

#2


5  

You can also try to avoid using backend if no localisation required:

如果不需要本地化,也可以尽量避免使用后端:

var comentsNumber = function(num){
  return (num == 0 || num > 1) ? num + " Comments" : num + " Comment"
};
var domObject = $('#<%= @card_id %> .card-comments-title');

Basically you can easily update an object via the AJAX call and trigger content to reload:

基本上,您可以通过AJAX调用轻松地更新对象,并触发内容重新加载:

var htmlContent = comentsNumber(<%= @comment_count %>);
domObject.html(htmlContent);

#3


3  

A possible better solution to display singular/plural text would be via i18n. You could try something like following:

一种更好的显示单复数文本的方法是通过i18n。你可以试试以下方法:

# config/locales/en.yml

en:
  comments:
    zero: No comments
    one: 1 comment
    other: %{count} comments

Then in your view, you'd use it as:

那么在你看来,你应该把它当作:

$('#<%= @card_id %> .card-comments-title').html("<%= t('comments', count: @node.comments_count) %>");

On the problem with helpers not working: Given that you have dashboard_helper.rb in app/helpers/ directory, your helper should work. With the problem you've described where the following line works:

关于helper函数不工作的问题:假设您有dashboard_helper函数。rb在app/helper / directory中,助手应该工作。对于你所描述的问题,下面的线是如何工作的:

$('#<%= @card_id %> .card-comments-title').html('<%= @comment_count %> Comments');

and the following doesn't:

和下面的不:

$('#<%= @card_id %> .card-comments-title').html('<%= show_number_of_comments(@node) %>');

You might find a better answer if you had the output of show_number_of_comments(@node) perhaps using console.log. It is likely that this output needs to be escaped using escape_javascript. So, although not a concrete solution, I'd suggest you to try:

如果使用console.log输出show_number_of_comments(@node),您可能会找到更好的答案。很可能需要使用escape_javascript来转义这个输出。所以,尽管不是一个具体的解决方案,我建议你尝试:

$('#<%= @card_id %> .card-comments-title').html('<%= j show_number_of_comments(@node) %>');

#4


1  

Edit: For Rails 3.1+, the following is only true if

编辑:对于Rails 3.1+,只有当

config.action_controller.include_all_helpers = false

Your DashboardHelper is included in the DashboardController. Your .js.erb seems to belong to something like CommentsController.

DashboardHelper包含在DashboardController中。. js。erb似乎属于注释控制器之类的东西。

You will either have to move your helper method to your ApplictionController or include the helper using helper DashboardHelper in the controller you want to use it in.

您将不得不将helper方法移动到ApplictionController,或者在您希望使用它的控制器中包含使用helper DashboardHelper的helper函数。

#5


0  

You could try pluralize:

你可以尝试兼职:

$('#<%= @card_id %> .card-comments-title').html('<%= pluralize(@comment_count, 'Comment') %>');

It should work in both places.

它应该在这两个地方都有效。

I missed your own followup.

我错过了你的后续报道。

I'd suggest moving helpers that you need in multiple contexts to the application_helper.rb file. Maybe not the best practice but it would do the job.

我建议将您在多个上下文中需要的助手迁移到application_helper。rb文件。也许不是最好的做法,但它会起到作用。

#6


0  

Try using j short for escape_javascript.

尝试使用jshort来实现escape_javascript。

$('#<%= @card_id %> .card-comments-title').html('<%= j show_number_of_comments(@node) %>');

#1


5  

So I figured out what I wanted to do in my specific case, i.e. pluralize comment count within my JS ERB, but I haven't figured out how to use a helper_method from within my JS ERB - so this answer doesn't really answer this question.

所以我找到了我想要在我的特定情况下做的事情,即在我的JS ERB中使用复数注释计数,但是我还没有找到如何在我的JS ERB中使用helper_method——所以这个答案并没有真正回答这个问题。

However, I am documenting this here in case someone else has a similar issue and my solution helps them.

然而,我在这里记录这些,以防其他人有类似的问题,我的解决方案可以帮助他们。

In my JS ERB, all I did was used the Rails method pluralize. I completely forgot about it until I typed up this question and it works like a charm.

在我的JS ERB中,我所做的一切都是使用Rails方法多元化。我完全忘记了,直到我输入了这个问题,它就像一个魅力。

Here is the code snippet for my create.js.erb:

这是我的create.j .erb的代码片段。

$('#<%= @card_id %> .card-comments-title').html('<%= pluralize(@comment_count, "Comment") %>');

Works like a charm, but this still doesn't answer my question about referencing/using helper methods here.

工作起来像一个魅力,但这仍然没有回答我的问题,关于引用/使用助手方法。

#2


5  

You can also try to avoid using backend if no localisation required:

如果不需要本地化,也可以尽量避免使用后端:

var comentsNumber = function(num){
  return (num == 0 || num > 1) ? num + " Comments" : num + " Comment"
};
var domObject = $('#<%= @card_id %> .card-comments-title');

Basically you can easily update an object via the AJAX call and trigger content to reload:

基本上,您可以通过AJAX调用轻松地更新对象,并触发内容重新加载:

var htmlContent = comentsNumber(<%= @comment_count %>);
domObject.html(htmlContent);

#3


3  

A possible better solution to display singular/plural text would be via i18n. You could try something like following:

一种更好的显示单复数文本的方法是通过i18n。你可以试试以下方法:

# config/locales/en.yml

en:
  comments:
    zero: No comments
    one: 1 comment
    other: %{count} comments

Then in your view, you'd use it as:

那么在你看来,你应该把它当作:

$('#<%= @card_id %> .card-comments-title').html("<%= t('comments', count: @node.comments_count) %>");

On the problem with helpers not working: Given that you have dashboard_helper.rb in app/helpers/ directory, your helper should work. With the problem you've described where the following line works:

关于helper函数不工作的问题:假设您有dashboard_helper函数。rb在app/helper / directory中,助手应该工作。对于你所描述的问题,下面的线是如何工作的:

$('#<%= @card_id %> .card-comments-title').html('<%= @comment_count %> Comments');

and the following doesn't:

和下面的不:

$('#<%= @card_id %> .card-comments-title').html('<%= show_number_of_comments(@node) %>');

You might find a better answer if you had the output of show_number_of_comments(@node) perhaps using console.log. It is likely that this output needs to be escaped using escape_javascript. So, although not a concrete solution, I'd suggest you to try:

如果使用console.log输出show_number_of_comments(@node),您可能会找到更好的答案。很可能需要使用escape_javascript来转义这个输出。所以,尽管不是一个具体的解决方案,我建议你尝试:

$('#<%= @card_id %> .card-comments-title').html('<%= j show_number_of_comments(@node) %>');

#4


1  

Edit: For Rails 3.1+, the following is only true if

编辑:对于Rails 3.1+,只有当

config.action_controller.include_all_helpers = false

Your DashboardHelper is included in the DashboardController. Your .js.erb seems to belong to something like CommentsController.

DashboardHelper包含在DashboardController中。. js。erb似乎属于注释控制器之类的东西。

You will either have to move your helper method to your ApplictionController or include the helper using helper DashboardHelper in the controller you want to use it in.

您将不得不将helper方法移动到ApplictionController,或者在您希望使用它的控制器中包含使用helper DashboardHelper的helper函数。

#5


0  

You could try pluralize:

你可以尝试兼职:

$('#<%= @card_id %> .card-comments-title').html('<%= pluralize(@comment_count, 'Comment') %>');

It should work in both places.

它应该在这两个地方都有效。

I missed your own followup.

我错过了你的后续报道。

I'd suggest moving helpers that you need in multiple contexts to the application_helper.rb file. Maybe not the best practice but it would do the job.

我建议将您在多个上下文中需要的助手迁移到application_helper。rb文件。也许不是最好的做法,但它会起到作用。

#6


0  

Try using j short for escape_javascript.

尝试使用jshort来实现escape_javascript。

$('#<%= @card_id %> .card-comments-title').html('<%= j show_number_of_comments(@node) %>');