Rails:获取下一个/上一个记录 [英] Rails: Get next / previous record
本文介绍了Rails:获取下一个/上一个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用有属于用户的照片.
My app has Photos that belong to Users.
在 photo#show 视图中,我想显示来自该用户的更多信息",并显示来自该用户的下一张和上一张照片.如果这些是 id
顺序中的下一张/上一张照片或 created_at
顺序中的下一张/上一张照片,我会很好.
In a photo#show view I'd like to show "More from this user", and show a next and previous photo from that user. I would be fine with these being the next/previous photo in id
order or the next/previous photo in created_at
order.
您将如何为下一张/上一张照片或多张下一张/上一张照片编写这种查询?
How would you write that kind of query for one next / previous photo, or for multiple next / previous photos?
推荐答案
试试这个:
class User
has_many :photos
end
class Photo
belongs_to :user
def next
user.photos.where("id > ?", id).first
end
def prev
user.photos.where("id < ?", id).last
end
end
现在您可以:
photo.next
photo.prev
这篇关于Rails:获取下一个/上一个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文