【问题标题】:I want to have a next and previous link that featches the next and previous article我想有一个下一个和上一个链接,它包含下一篇和上一篇文章
【发布时间】:2015-10-16 08:22:39
【问题描述】:

在一个简单的博客应用程序中,某人可以阅读一篇文章并决定阅读下一篇文章,而无需再次浏览文章列表,但单击下一步按钮,此人将转到此列表中的下一篇文章。如何才能做到这一点。我使用过 willpaginate 和 kaminari,它们都是很棒的分页插件。

所以现在在显示操作中,我想要一个下一个和上一个链接,该链接与下一篇和上一篇文章相匹配,我该怎么做

使用下面的简单代码示例

def show
  @article = Article.find(params[:id])
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 pagination will-paginate


    【解决方案1】:

    您可以向Article 添加一个方法来获取下一篇和上一篇文章,具体取决于您所说的下一篇和上一篇 - 即您希望文章的顺序。

    例如用created_at定义顺序

    def next
      self.class.find(
        :first, 
        :conditions => ["created_at > ?", self.created_at], 
        :order => 'created_at, id')
    end
    
    def previous
      self.class.find(
        :first, 
        :conditions => ["created_at < ?, self.created_at],
        :order => 'created_at desc, id desc')
    

    假设在 date 没有创建相同的内容,这可能有点过于简单,因此您可能也想检查 id。比如:

        :conditions => ["created_at > ? or (created_at = ? and id > ?)", self.created_at, self.created_at, self.id]
    

    如果您只想按 id 订购,那么它就更简单了,因为 id 永远不会相同:

    def next
      self.class.find(:first,
        :conditions => ['id > ?', self.id],
        :order => 'id')
    end
    
    def previous
      self.class.find(:first,
        :conditions => ['id < ?', self.id],
        :order => 'id desc')
    end
    

    【讨论】:

    • 我不想对数组列表进行分页我只想去一个 artiscl 并阅读而不是去索引操作来查看更多我想通过单击下一步按钮阅读下一篇文章所以它会得到 ID 高于我正在阅读的文章的文章
    • 是的,我就是这么想的。所以在你的展示页面上你可以做link_to("Next", article_url(@article.next))。如果您只需要 id,那么您的条件就更容易了,您只需检查 id 是否大于您拥有的 id 并按 id 排序。
    • 我更新了我的答案,举了一个例子,只使用 id 来检索下一篇和上一篇文章。
    • 我在页面底部test.tektweet.com/stories/… 实现了您的解决方案
    【解决方案2】:

    您可以使用 Willpaginate 插件来解决您的问题。 https://github.com/mislav/will_paginate

    【讨论】:

    • 我不想对数组列表进行分页我只想去一个 artiscl 并阅读而不是去索引操作来查看更多我想通过单击下一步按钮阅读下一篇文章所以它会得到 ID 高于我正在阅读的文章的文章。
    • OP 在问题中提到了 will_paginate gem。
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    相关资源
    最近更新 更多