Forum: Ruby on Rails next and previous methods for a model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2008-11-21 01:50
(Received via mailing list)
Anyone know of a plugin or gem that would create methods such as next
and previous on a model to traverse among siblings? For example,
@post.next and @post.prev.
gsterndale (Guest)
on 2008-11-21 09:37
(Received via mailing list)
I don't know of any, sorry.

In the past I've written two simple instance methods and two
named_scopes in my models.

named_scope :next, lambda {|post, user|
  { :conditions => ["created_at > ? and user_id = ?", post.created_at,
user.id], :order => "created_at ASC" }
}

named_scope :prev, lambda {|post, user|
  { :conditions => ["created_at < ? and user_id = ?", post.created_at,
user.id], :order => "created_at DESC" }
}

def next(user)
  Post.next(self, user).first
end

def prev(user)
  Post.prev(self, user).first
end
MaD (Guest)
on 2008-11-21 10:44
(Received via mailing list)
you could try acts_as_list
This topic is locked and can not be replied to.