Rails: Get next / previous record

前端 未结 9 1014
说谎
说谎 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:05

    class Photo < ActiveRecord::Base
      belongs_to :user
    
      default_scope { order('published_at DESC, id DESC') }
    
      def next
        current = nil
        user.photos.where('published_at >= ?', published_at).each do |p|
          if p.id == id then break else current = p end
        end
        return current
      end
    
      def previous
        current = nil
        user.photos.where('published_at <= ?', published_at).reverse.each do |p|
          if p.id == id then break else current = p end
        end
        return current
      end
    end
    

    I found that the answers already here did not serve my case. Imagine that you want a previous or next based on the date published, but some photos are published on the same date. This version will loop through the photos in the order they are rendered on the page, and take the ones before and after the current one in the collection.

提交回复
热议问题