I'm attempting to create a button on the show
page that will allow users to navigate between different comments.
And for some reason, I keep getting either article :id
or comment :id
could not be found.
Any idea why that happens?
#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)
EDIT: The problem was in my routes, which has now been fixed. But now I get the following error:
undefined method "next" for nil:NilClass
EDIT 2:
Here's the log--and the URL goes to http://localhost:3000/articles/14/comments/56/next_comment
Now it doesn't raise any errors but simply displays a blank page instead of going to the next comment URL which is 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)
The @scope
instance variable is undefined (and therefore nil
) prior to you using it. Just change it to the following and it should work
def next_comment
@next_comment = scope.next(@comment)
end
def scope
@scope ||= @article.comments
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.