Ruby/Rails Features and Patterns

Flashcard 5 of 6

Is there anything we can add to the migration below so that Posts are guaranteed to have referential integrity (meaning a post's user_id will always point to a user row that actually exists in the database)?

class AssociatePostsWithUsers < ActiveRecord::Migration
  def change
    add_column :posts,
               :user_id,
               null: false,
               index: true
  end
end

We can ensure referential integrity by adding a foreign key constraint (a feature available as of Rails 4.2):

class AssociatePostsWithUsers < ActiveRecord::Migration
  def change
    add_column :posts,
               :user_id,
               null: false,
               index: true

    # This part is new:
    add_foreign_key :posts,
                    :users
  end
end

class User
  # We'll also want to add the dependent delete below.
  has_many :posts,
           dependent: :delete
end

Now, our database won't let us get to a state where post.user_id refers to a user that doesn't exist. Sweet, sweet, database-enforced safety.

For a more-detailed look at this feature, check out this blog post.

Return to Flashcard Results