DEV Community

Ngan Kim Khong
Ngan Kim Khong

Posted on

Ruby - reference and foreign keys

There are several ways to add foreign key into our Ruby models. I have tried some of them. Some have been working fine but there are always cases where it does not work and I don't know why. However, I have found a way to add the foreign key that always work perfectly.

Let's say, for my model, a user has many playlists, and a playlist belongs to one user. This is the command that I should be running in the terminal:

rails g migration AddUserRefToPlaylist user:references

That's it. Happy coding.

Top comments (1)

Collapse
 
tadman profile image
Scott Tadman

The migration generator does a ton of neat stuff but you really do need a cheat-sheet to remember how. Neat trick!