DEV Community

Cover image for Multiple Foreign Keys for the Same Relationship in Rails 6

Multiple Foreign Keys for the Same Relationship in Rails 6

Lucas Hiago on June 14, 2020

It’s quite easy to create tables with Ruby On Rails. However, some cases require personalizations to reproduce real world situations and the relati...
Collapse
 
jelilfaisalabudu profile image
JelilFaisalAbudu

@luchiago , thanks for the wonderful post of yours. You saved me from a big headache. I was wondering whether or not I would be able to find a post on this particular topic for Rails v6. Yeah, I'm now learning the basics, you know? Thanks man

Collapse
 
luchiago profile image
Lucas Hiago

Hey @jelilfaisalabudu , I appreciate your feedback and that I could help you! Stay strong and keep learning every day.

Collapse
 
chase439 profile image
Chase

Could you add "inverse_of" to your examples?

Collapse
 
luchiago profile image
Lucas Hiago

Why it's necessary?

Collapse
 
chase439 profile image
Chase

Rubocop would complain if you don't have it.

Collapse
 
chase439 profile image
Chase

If you have data in these tables (e.g. when changing the tables instead of creating them), you need to make sure the columns have valid values before adding foreign key constraints.

Collapse
 
luchiago profile image
Lucas Hiago

You mean, for the available_user and requester_user variables?

Collapse
 
chase439 profile image
Chase

I mean data records in these tables (not variables).

Collapse
 
sorinaduca profile image
Sorina Duca

Thanks a lot for the great post! I was just building this and it was hard to wrap my mind around it. Your post scratches the exact itch!

Collapse
 
luchiago profile image
Lucas Hiago

Glad to hear this!

Collapse
 
amartinezre05 profile image
Albéniz

@luchiago Thanks! I spent much time today trying to solve this