Rails:“下一篇文章"和“上一篇"我的节目视图中的链接,如何? [英] Rails: "Next post" and "Previous post" links in my show view, how to?

查看:37
本文介绍了Rails:“下一篇文章"和“上一篇"我的节目视图中的链接,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 新手......微笑

I'm new in Rails... smile

在我的博客应用程序中,我希望在我的节目视图底部有一个上一篇文章"链接和一个下一篇文章"链接.

In my blog aplication I want to have a "Previous post" link and a "Next post" link in the bottom of my show view.

我该怎么做?

谢谢!

推荐答案

如果每个标题都是唯一的并且您需要按字母顺序排列,请在您的 Post 模型中尝试这个.

If each title is unique and you need alphabetical, try this in your Post model.

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

然后您可以链接到视图中的那些.

You can then link to those in the 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_atid 等).

Untested, but it should get you close. You can change title to any unique attribute (created_at, id, etc.) if you need a different sort order.

这篇关于Rails:“下一篇文章"和“上一篇"我的节目视图中的链接,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆