Ruby on Rails:评论之间的导航

时间:2016-02-24 18:35:23

标签: ruby-on-rails ruby

我正在尝试在show页面上创建一个按钮,允许用户在不同的评论之间导航。

由于某些原因,我无法找到article :idcomment :id

知道为什么会这样吗?

#comment.rb

def self.next(comment, key = :id)
  self.where("#{key} > ?", comment.send(key)).first
end


#comments_controller.rb
class CommentsController < ApplicationController

  before_action :find_article
  before_action :find_comment

  def next_comment 
    @next_comment = @scope.next(@comment)
  end

  def scope
    @scope = @article.comments
  end
end

#comments/show.html.haml
= link_to "Next Comment", comments_next_comment_path(@next_comment)

编辑:问题出在我的路线上,现在已经修好了。 但现在我收到以下错误:

undefined method "next" for nil:NilClass

编辑2:

以下是日志 - 网址转到http://localhost:3000/articles/14/comments/56/next_comment

现在它不会引发任何错误,只是显示一个空白页而不是转到下一个评论网址http://localhost:3000/articles/14/comments/70

 Parameters: {"article_id"=>"14", "id"=>"56"}
  Article Load (0.2ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1  [["id", 14]]
  Comment Load (0.1ms)  SELECT  "comments".* FROM "comments" WHERE "comments"."id" = ? LIMIT 1  [["id", 56]]
  Rendered comments/next_comments.html.haml within layouts/application (0.2ms)

1 个答案:

答案 0 :(得分:1)

@scope实例变量在您使用之前未定义(因此nil)。只需将其更改为以下内容即可正常工作

def next_comment
  @next_comment = scope.next(@comment)
end

def scope
  @scope ||= @article.comments
end