DEV Community

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

Collapse
juanmanuelramallo profile image
Juan Manuel Ramallo

Assuming a Book class exist and it has many chapters, and also assuming that the chapter has a position number stored in the database, I'd do something like:

class Chapter < ApplicationRecord
  belongs_to :book

  def next_chapter
    book.chapters.find_by(position: position + 1)
  end

  def previous_chapter
    book.chapters.find_by(position: position - 1)
  end
end