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. H...
For further actions, you may consider blocking this person and/or reporting abuse
guides.rubyonrails.org/association...
Thanks Brian for the reply!
Why is the
foreign_key
theprevious_chapter_id
and not something likenext_chapter_id
?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.
Ahhh clever, thanks Brian for the help. I implemented this method and it worked as you described it :)
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
instancesThanks Miguel for the tip on setting up the method :) this is super helpful.
Happy to help :)
Is there a parent object like
book
?Let's assume no.
I would go with Brianβs solution then. The other solutions work, but I would prefer to have a strong reference, in this case a foreign key stored in the Database.
Yup that's the solution that I ended up going with. Thanks Christopher for the help!
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:I'd question whether a method like this should sit in the model (should it actually have knowledge of its sibling persisted objects? Usually not)
Depending on your context, making a small class/service/whatever which determines position might be more suitable (and easier to test/maintain).