I have two models, Story and Chapter. A story has_many chapters, one of those is a chapter which serves as its first chapter. I used to have a foreign key start_id in the stories table to indicate which chapter is the first. Hovewer, the the database schema had to be changed a little, now every chapter has a code. If the code is '1a', then that is first chapter of the story which owns the chapter.
The following seems to work, including #create_start:
has_many :chapters, :dependent => :destroy, :inverse_of => :story
has_one :start, :class_name => 'Chapter', :foreign_key => 'story_id', :conditions => {:code => '1a'}
This way, the foreign key start_id of the stories table is unneeded, and #start still remains an association, with all the benefits (I need #start as an association, because I use CanCan with associations for authorization).
Does my approach has any drawbacks that I currently fail to realize, or I am relatively safe with it?
Relying on the code == ‘1a’ to find the first chapter is a bit wonky. I’d probably add a flag to the chapters table like ‘first_chapter’ or something that was true or false indicating whether it was the first chapter. This way the first_chapter-ness of a chapter would survive a change to the code field, but this is a bit nitpicky.
Also, to avoid repeating yourself, you could change the declaration of has_one :start to something like: