Next post 在转到博客中的第一条记录时中断

Next post breaks when going to the first record in the blog

我什至不知道如何表达这个问题。我有一个带有提要的博客。当有人点击显示页面时,我希望在右侧边栏中有一个 link 和下一篇文章的图片。当它到达数据库中的第一篇文章或最新的文章时,我要么不希望 link 带有图片,要么不希望数据库中最古老的故事循环返回。

我有代码可以获取下一篇文章并显示带有 link 的封面照片。如果有人可以帮助我为数据库中的第一篇文章编写条件,这样我就不会出错,那就太好了。这是我的代码:

展示页面:

  <div id="next-story-sidebar">
      <%= link_to "next story", @next_home_blog, style: "font-size:20px;" %>
      <%= image_tag @next_home_blog.image.to_s, style: "width:60px;height:60px;" %>
  </div>

home_blog.rb

def next
    self.class.where("id > ?", id).first
  end

  def previous
    self.class.where("id < ?", id).last
  end

  def last
    self.class.where("id = ?", id).last 
  end



   home_blogs_controller.rb 

  def show
    @home_blog = HomeBlog.find(params[:id])
    @next_home_blog = @home_blog.next
  end

当我点击下一篇文章 link 时出错,这将我带到数据库中的第一篇文章:nil:NilClass

的未定义方法“图像”

这是因为您的查询需要一个基本案例。

self.class.where("id > ?", id).first

问题是,如果您的 ID 为 1、2、3 并且您在数字 3 上。这将 return 一个 0 长度的集合,并且首先在一个空集合上它是 nil。

要解决这个问题,您可以在您的应用程序的任何地方进行 nil 检查

<% if @next_home_blog %>
  <div id="next-story-sidebar">
    <%= link_to "next story", @next_home_blog, style: "font-size:20px;" %>
    <%= image_tag @next_home_blog.image.to_s, style: "width:60px;height:60px;" %>
  </div>
<% end %>

或者做一些事情 return NullBlog 来表示该概念并以更面向对象的方式处理它。如果您想调查 NullObject 模式,这里有一个 link 可以帮助您入门。 https://robots.thoughtbot.com/rails-refactoring-example-introduce-null-object