我是 Rails 的新手......微笑
在我的博客应用程序中,我希望在我的节目 View 底部有一个“上一篇文章”链接和一个“下一篇文章”链接。
我该怎么做呢?
谢谢!
最佳答案
如果每个标题都是唯一的并且您需要按字母顺序排列,请在您的 Post
中尝试此操作模型。
def previous_post
self.class.first(:conditions => ["title < ?", title], :order => "title desc")
end
def next_post
self.class.first(:conditions => ["title > ?", title], :order => "title asc")
end
然后,您可以链接到 View 中的那些。
<%= link_to("Previous Post", @post.previous_post) if @post.previous_post %>
<%= link_to("Next Post", @post.next_post) if @post.next_post %>
未经测试,但它应该让你接近。您可以更改
title
如果您需要不同的排序顺序,可以添加到任何唯一属性( created_at
、 id
等)。
关于ruby-on-rails - Rails : "Next post" and "Previous post" links in my show view, 怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1275963/