【问题标题】:refreshing rails helper method with ajax error刷新带有ajax错误的rails帮助方法
【发布时间】:2014-08-01 13:40:46
【问题描述】:

每次我尝试使用 rails ajax 更新辅助方法时,都会收到未定义的方法错误。

我的文章助手中有一个计数方法,用于计算一篇文章的所有 cmets:

def count 
@article = Article.find_by_slug(params[:id])
@comments = Comment.where(:article_id => @article.id)
@comments.count
end

然后我在我的文章显示视图中显示 cmets 的数量:

<span id="comments_count"><%= count %></span>

这一切都很好,但是当我尝试在我的 create.js.erb 文件中更新它时,我得到一个未定义的方法错误:

$('#comments_count').html('<%= escape_javascript(count) %>');

我收到的错误是:

ActionView::Template::Error (undefined method `id' for nil:NilClass):
    1: if ($(".replyform")[0]){
    2: $('.replyhere').after('<div class="comment"> <%= escape_javascript(render :partial => @comment) %> </div>');
    3: 
    4: $('#comments_count').html('<%= escape_javascript(count, locals: {count: @count}) %>');
    5: $('.replyform').removeClass('replyform');
    6: $('.replyhere').removeClass('replyhere');
    7:       $('.reply_form').fadeOut('fast', function() {
  app/helpers/articles_helper.rb:13:in `count'
  app/views/comments/create.js.erb:4:in `_app_views_comments_create_js_erb__499623995209914056_70100096787760'
  app/controllers/comments_controller.rb:11:in `create'

我尝试定义一些本地人,例如:

locals: {count: @count}

但这似乎也无济于事。

任何帮助将不胜感激。

【问题讨论】:

  • 在调用@article.id之前添加if语句检查是否有文章

标签: javascript jquery ruby-on-rails ruby ajax


【解决方案1】:

在调用@article.id之前添加if语句检查是否有文章

def count 
  @article = Article.find_by_slug(params[:id])
  if @article
    @comments = Comment.where(:article_id => @article.id)
    @comments.count
  else
    # Do something
  end
end

【讨论】:

  • 这样可以解决错误,但不能解决没有收到@article 的问题?
  • 也许它不是您在尝试 find_by_slug 时想要搜索的 ID 参数,我怀疑它是一个 ID。ID 只能在普通 .find 方法中使用,而不是 .find_by_slug
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 2015-10-11
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多