Rails: Get next / previous record

前端 未结 9 1009
说谎
说谎 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 17:57

    Modify your app/models/application_record.rb to the following code:

    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    
      def next
        self.class.where("id > ?", id).order("id ASC").first || self.class.first
      end
    
      def previous
       self.class.where("id < ?", id).order("id DESC").first || self.class.last
      end
    end
    

    Then you can use next() and previous() in all your models.

提交回复
热议问题