DEV Community

loading...

Ruby - reference and foreign keys

nk2303 profile image Ngan Kim Khong ・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)

pic
Editor guide
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!