DEV Community

Discussion on: How would you setup a model in Rails to reference the same model type?

Collapse
 
mickeytgl profile image
Miguel • Edited

in your app/models/chapter.rb

def next_chapter
  return self if self == Chapter.last 

  Chapter.find self.id +1
end

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 call next_chapter on your Chapter instances

Collapse
 
michael profile image
Michael Lee 🍕

Thanks Miguel for the tip on setting up the method :) this is super helpful.

Collapse
 
mickeytgl profile image
Miguel

Happy to help :)