Let's say I have a model for a thing called "Chapter". I want to be able to reference the next chapter and the previous chapter for each chapter. How would you go about setting this up?
So what I'm looking for is something like this:
c = Chapter.first
c.next_chapter
c.next_chapter
should return a chapter object that is the next chapter.
in your app/models/chapter.rb
Explanation:
The first line checks if the chapter that you called
next_chapter
on is the last one and if so, it just returns itself (You can change this to an error message or whatever you want). And if that's not the case, then we call find on chapter, which takes the Chapter ID as an argument and we just add one to the current ID. And voilà: Now you can callnext_chapter
on yourChapter
instances