Rails: Get next / previous record

前端 未结 9 1037
说谎
说谎 2020-12-07 17:48

My app has Photos that belong to Users.

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

9条回答
  •  醉酒成梦
    2020-12-07 18:04

    This should work, and I think it's more efficient than the other solutions in that it doesn't retrieve every record above or below the current one just to get to the next or previous one:

    def next
      # remember default order is ascending, so I left it out here
      Photo.offset(self.id).limit(1).first
    end
    
    def prev
      # I set limit to 2 because if you specify descending order with an 
      # offset/limit query, the result includes the offset record as the first
      Photo.offset(self.id).limit(2).order(id: :desc).last
    end
    

    This is my first answer ever posted on StackOverflow, and this question is pretty old...I hope somebody sees it :)

提交回复
热议问题