Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Get next / previous record

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 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?

like image 818
Andrew Avatar asked Sep 12 '11 21:09

Andrew


4 Answers

Try this:

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

Now you can:

photo.next
photo.prev
like image 183
Harish Shetty Avatar answered Oct 17 '22 15:10

Harish Shetty


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.

like image 24
Cremz Avatar answered Oct 17 '22 14:10

Cremz


Not sure if this is a change in Rails 3.2+, but instead of:

model.where("id < ?", id).first

for the previous. You have to do

.where("id > ?", id).last

It seems that the "order by" is wrong, so first give you the first record in the DB, because if you have 3 items lower than the current, [1,3,4], then the "first" is 1, but that last is the one you ware looking for. You could also apply a sort to after the where, but thats an extra step.

like image 8
jwilcox09 Avatar answered Oct 17 '22 16:10

jwilcox09


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 :)

like image 5
jinstrider2000 Avatar answered Oct 17 '22 14:10

jinstrider2000