如何选择博客模型中的最后一个条目和倒数第二个条目? [英] How do I pick the last and the second to last entries in a blog model?
问题描述
我有一个模型blog_posts,其中有一个字段"published_at".我想从该模型中选择最新的两个博客,以显示在我的主页上.不确定如何构造它.
I have a model, blog_posts which has a field "published_at". I'd like to select the latest two blogs from that model to display on my homepage. Not sure how to structure that though.
目前,我有一个解决方法,它需要一部分数据,但是当表中没有任何内容时,它一直会失败,而不是解决这个问题,我觉得可能有更好的方法来检索数据.
At the moment I have a work around that takes a slice of the data but it keeps failing when I have nothing in the table, rather than fix this I feel there is probably a better way to retrieve the data.
例如,我需要在单独的呼叫中选择博客
I need to select the blogs in separate calls, for example
@ blog_post.latestpost
, @ blog_post.secondlatestpost
推荐答案
这是您要找的东西吗?:
Is this what you're looking for? :
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
希望这会有所帮助.
这篇关于如何选择博客模型中的最后一个条目和倒数第二个条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!