Type a keyword and hit enter to start searching. Press Esc to cancel.

Currently Reading

Rails 4.2 Foreign Keys for Parent / Child Model Association

Referential integrity, it gives me that warm and fuzzy feeling inside.  That’s why I was so excited when Rails added support for managing foreign keys with ActiveRecord.  However, I got a little confused when implementing a foreign key on a Model that had an internal tree structure with self-referential parent/child associations.  Here’s the final implementation.

Take the following Model with a self-referential parent / child association:

class Category < ActiveRecord::BaseActiveRecord::Base
  belongs_to :parent, class: 'Category'
  has_many :children, class: 'Category', foreign_key: 'parent_id'
end

To add a foreign key for that association we would put the following in our migration:

add_reference :categories, :parent, index: true
add_foreign_key :categories, :categories, column: 'parent_id'

This will add a parent_id column to the categories table, index that column and specify the foreign key.  This will ensure we don’t have any Category that references a non-existent parent.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *