【问题标题】:How do I pick the last and the second to last entries in a blog model?如何选择博客模型中的最后一个和倒数第二个条目?
【发布时间】:2011-08-28 17:13:56
【问题描述】:

我有一个模型 blog_posts 有一个字段“published_at”。我想从该模型中选择最新的两个博客显示在我的主页上。不知道如何构建它。

目前我有一个解决方法可以获取数据片段,但是当我在表中没有任何内容时它会一直失败,而不是解决这个问题,我觉得可能有更好的方法来检索数据。

例如,我需要在单独的调用中选择博客

@blog_post.latestpost, @blog_post.secondlatestpost

【问题讨论】:

    标签: ruby-on-rails-3 activerecord


    【解决方案1】:

    这就是你要找的吗? :

    class BlogPost < Activerecord::Base
      def self.latestpost
        order("published_at DESC").limit(1).first
      end
    
      def self.secondlatestpost
        order("published_at DESC").offset(1).limit(1).first
      end
    end
    

    像这样使用它:

    BlogPost.secondlatestpost
    

    BlogPost.latestpost
    

    希望这会有所帮助。

    【讨论】:

    • 这会很好用!我试试看,谢谢我什至没有想过要这样写。
    • 假设我可以在 if 语句上运行一个 != nil ,这样一些代码如果不存在就不会加载?
    • 是的。需要注意的一件事是,当您在数据库中只有一条记录时。最后一个将返回记录,倒数第二个将返回 nil。
    • 如何在我的 if 中说明这一点?我试过 if @blog_post.secondlatestpost != nil 但它似乎仍然失败了 heroku - 奇怪的是它在我的开发机器上工作。这是与数据库相关的问题吗?我应该换个方式问吗?
    • 酷 - 工作!我没有另一个与我使用切片方法有关的错误,所以我将尝试使用你上面描述的方法来拉它:-)
    【解决方案2】:

    你也可以这样做:

    BlogPost.order(:published_at).last # for the last post
    BlogPost.order(:published_at).offset(1).last # for the second to last post
    

    【讨论】:

    • 完美的方式来做我正在寻找的东西。谢谢!
    【解决方案3】:

    从 Rails 5 开始,您可以使用 BlogPost.second_to_last

    http://api.rubyonrails.org/v5.0/classes/ActiveRecord/FinderMethods.html#method-i-second_to_last

    【讨论】:

    • 是的。就是这样。就是这样!
    【解决方案4】:

    至少从 Rails 4.x 开始,你可以指定你想要的最后一条记录。例如。获取最后 2 条记录:

    BlogPost.last(2)
    

    first() 也是如此。还有方法second()third()fourth()fifth()forty_two()。从 Rails 5.x 开始,second_to_last()third_to_last()

    【讨论】:

      【解决方案5】:

      你也可以使用 ActiveRecord

      BlogPost.order("published_at DESC").second
      

      虽然我认为使用offsetlimit 是更干净、更便携的版本。在内部second(和thirdfourth)使用find_nths 方法。记录在这里: http://apidock.com/rails/ActiveRecord/FinderMethods/second

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-18
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        相关资源
        最近更新 更多