Search code examples
ruby-on-railsactiverecordrails-migrations

Model a fork relationship within ActiveRecord


What does the ActiveRecord::Migration and ActiveRecord::Base look like for a class that references itself. I'm modeling an object that "forks" off an existing record and stores that relation in a :source field. That :source field will contain the primary_key :id of it's parent.


Solution

  • ActiveRecord doesn't include a "predefined" relation of this type, but you can define it yourself using the has_many and belongs_to helpers. You would need to add a foreign key, e.g. my_parent_id to the model (I'll call it Thing):

    rails g migration AddMyParentIdToThings my_parent:references
    

    Then you would need to define the relation specifying the foreign key and class names:

    class Thing < ActiveRecord::Base
      belongs_to :parent_thing, class_name: "Thing", foreign_key: :my_parent_id
      has_many :child_things, class_name: "Thing", foreign_key: :my_parent_id
    end
    

    You can omit the :foreign_key option on the belongs_to (not the has_many) if the foreign key matches the relation name with an appended "_id" e.g.:

    belongs_to :my_parent, class_name: "Thing"