DEV Community

loading...

Ruby - reference and foreign keys

Ngan Kim Khong
Hi! I'm currently a software engineer intern! I am looking to post some blogs about what I'm learning :)
・1 min read

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.

Discussion (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!