Rails: Get next / previous record

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

    It lead me to a solution for my problem as well. I was trying to make a next/prev for an item, no associations involved. ended up doing something like this in my model:

      def next
        Item.where("id > ?", id).order("id ASC").first || Item.first
      end
    
      def previous
        Item.where("id < ?", id).order("id DESC").first || Item.last
      end
    

    This way it loops around, from last item it goes to the first one and the other way around. I just call @item.next in my views afterwards.

提交回复
热议问题