Skip to content


Rails/ActiveRecord acts_as_list #first() and #last()

Recently, I created a little photo album, and needed to have it ‘loop’. In other words, when you were looking at the first photo in the album, the ‘previous’ link would go to the last photo album.

class Photo < ActiveRecord::Base
  belongs_to :photo_album
  acts_as_list :scope => :photo_album
  
  def last
    Photo.find(:first, :conditions => ['position = (SELECT max(position) FROM photos WHERE photo_album_id = ?) AND photo_album_id = ?', self.photo_album_id, self.photo_album_id])
  end
  
  def first
    Photo.find(:first, :conditions => ['position = (SELECT min(position) FROM photos WHERE photo_album_id = ?) AND photo_album_id = ?', self.photo_album_id, self.photo_album_id])
  end
end

Basically I just ask for the max() and min() positions of the photo album.

Posted in Rails, Tips and Tricks.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.