I wanted to add a foreign key to an existing table using Rails’ references feature but this was not an option for existing tables. The good news is that Rails 4 makes it possible.

I prefer references because it allows you to be lazy by automatically adding the foreign key and index.

$ rails g migration AddUserRefToProducts user:references

This migration will add a user_id column to your products table and index it.

Comments