【发布时间】: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