DEV Community

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

Collapse
 
briankephart profile image
Brian Kephart

guides.rubyonrails.org/association...

# in migration
def change
  add_reference :chapters, :previous_chapter, foreign_key: { to_table: :chapters }
end

# chapter.rb
belongs_to :previous_chapter, class_name: Chapter
has_one :next_chapter, class_name: Chapter, foreign_key: :previous_chapter_id
Enter fullscreen mode Exit fullscreen mode
Collapse
 
michael profile image
Michael Lee 🍕

Thanks Brian for the reply!

has_one :next_chapter, class_name: ‘Chapter’, foreign_key: :previous_chapter_id

Why is the foreign_key the previous_chapter_id and not something like next_chapter_id?

Collapse
 
briankephart profile image
Brian Kephart

Because that’s a reference to the database column in your migration. That line basically says, “When the :next_chapter method is called, return the chapter that lists this one as its :previous_chapter.”

You could set up the migration to store the next chapter instead of the previous one. It’s the same process. I just thought it makes more sense this way because when you create a chapter, the previous one probably exists already, whereas the next one might not.

Thread Thread
 
michael profile image
Michael Lee 🍕

Ahhh clever, thanks Brian for the help. I implemented this method and it worked as you described it :)