按最近日期调用实例 rails
Call an instance by most recent dates rails
我有一组博客post,我想按最近日期的顺序显示它们。我如何在控制器中调用该方法
我试过了
@post1 = Post.last
但是我该怎么做前 3 个呢?
这应该能满足您的需求:
@post1 = Post.last(4).reverse[0..-2]
Post.last(4).reverse
将按降序为您提供最后 4 条记录。然后,这样: Post.last(4).reverse[0..-2]
除了最后一个你想要的元素,你正在抓住所有元素。
如果您不想要 descending
顺序,那么您可以不使用 reverse
部分:
@post1 = Post.last(4)[0..-2]
希望对您有所帮助。
更新
你也可以这样做:
@posts = Post.limit(4).order(updated_at: :desc)[1..-1]
这个:
@post1 = Post.last
并没有像您认为的那样给出最后一个 Post
。如果您检查日志,您会看到类似这样的内容:
selector={"$query"=>{}, "$orderby"=>{:_id=>-1}}
所以它将是 "last in id
order",而不是最后一个日期。如果你想要最后一个时间戳,那么你必须这样说:
@post1 = Post.order(:created_at => :desc).first
如果您有更符合您意图的日期或时间戳,您可以使用其他日期或时间戳而不是 :created_at
。
现在,如果你想要前面的三个,拿四个扔掉一个:
other_three = Post.order(:created_at => :desc).limit(4)[1.3] # or any of the ways
或者您可以使用 offset
跳过第一个:
other_three = Post.order(:created_at => :desc).offset(1).limit(3)
我有一组博客post,我想按最近日期的顺序显示它们。我如何在控制器中调用该方法
我试过了
@post1 = Post.last
但是我该怎么做前 3 个呢?
这应该能满足您的需求:
@post1 = Post.last(4).reverse[0..-2]
Post.last(4).reverse
将按降序为您提供最后 4 条记录。然后,这样: Post.last(4).reverse[0..-2]
除了最后一个你想要的元素,你正在抓住所有元素。
如果您不想要 descending
顺序,那么您可以不使用 reverse
部分:
@post1 = Post.last(4)[0..-2]
希望对您有所帮助。
更新
你也可以这样做:
@posts = Post.limit(4).order(updated_at: :desc)[1..-1]
这个:
@post1 = Post.last
并没有像您认为的那样给出最后一个 Post
。如果您检查日志,您会看到类似这样的内容:
selector={"$query"=>{}, "$orderby"=>{:_id=>-1}}
所以它将是 "last in id
order",而不是最后一个日期。如果你想要最后一个时间戳,那么你必须这样说:
@post1 = Post.order(:created_at => :desc).first
如果您有更符合您意图的日期或时间戳,您可以使用其他日期或时间戳而不是 :created_at
。
现在,如果你想要前面的三个,拿四个扔掉一个:
other_three = Post.order(:created_at => :desc).limit(4)[1.3] # or any of the ways
或者您可以使用 offset
跳过第一个:
other_three = Post.order(:created_at => :desc).offset(1).limit(3)