我甚至不知道怎么表达这个问题。我有个博客,里面有个提要。当一个人点击到显示页面时,我希望有一个链接到右边边栏中的下一篇文章。当它到达数据库中的第一篇文章或最新的一篇文章时,我要么不想要一个带有图片的链接,要么一个到数据库中最古老的故事的链接来循环。
我有代码工作在哪里,它得到下一篇文章,并显示它的封面照片与它的链接。如果有人能帮我为数据库中的第一篇文章写一篇文章,那么我就不会得到很好的错误。下面是我的代码:
节目页面:
<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当我单击下一个故事链接时出错,该链接带我到数据库中的第一篇文章:未定义的方法‘`image’for nil:NilClass
发布于 2018-09-23 17:45:59
这是因为您需要一个基本大小写来查询。
self.class.where("id > ?", id).first
问题是,如果你的id是1,2,3,并且你在3号,这将返回一个0长度集合,第一个是空集合,它是零。
要解决这个问题,您可以在应用程序中的任何地方执行零检查。
<% 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 %>或者,返回一个NullBlog来表示这个概念,并处理它更多的OO样式。这里有一个指向NullObject模式的链接,如果您想研究这个模式,就可以启动它。https://robots.thoughtbot.com/rails-refactoring-example-introduce-null-object
https://stackoverflow.com/questions/52468317
复制相似问题