按创建时间排序,包含下一个和上一个帖子链接

时间:2014-07-16 11:13:44

标签: ruby-on-rails ruby

从这里的其他问题和答案,我可以看到创建'下一步'和'以前'链接你可以做到这一点

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

如果它们是唯一的,它将按标题排序..我不太了解条件语法,并且想知道是否有人可以解释它。

如果我想按created_at日期订购,我可以将订单更改为created_at desc和created_at asc,但那么我的条件是什么?

任何帮助表示赞赏

由于

1 个答案:

答案 0 :(得分:1)

如果您在轨道4上,那么您可以:

def previous_post
  self.class.where("created_at < ?", created_at).order(created_at: :desc).first
end

def next_post
  self.class.where("created_at > ?", created_at).order(created_at: :asc).first
end