In Ruby on Rails, foreign keys are used to establish associations between different models. They allow you to link records in one table to records in another table. These foreign keys create relationships between tables. Although sometimes you may need to have two different keys from the same model in a new model. In this blog post, I'm going to briefly demonstrate how to use foreign keys in Ruby on Rails to do it.
Let's say you have a "User" model, and you want to create a new model called "Meeting" to store information about meetings between users. Each user will have need a unique foreign key. Lets call the foreign keys "sender_id" and "receiver_id". Both of which will use the "id" column in the "User" model.
Now the first place to start when must creating this association is the new model.
Create the "Meeting" model:
First, we need to create a new model called "Meeting" using the Rails generator:
This will create a new migration file for the "Meeting" model. Now we need to go into the migration file to update that before migrating.
Update the migration file:
Now we need to update the migration file to have foreign keys. One for the user receiving the meeting and one for the user sending the meeting. The foreign keys of "receiver_id" and "sender_id" will allow the user id to be passed as an alias to the meeting table twice one user as a receiver and one user as a sender.
Then run "rail db:migrate"
Update the models:
Finally, we need to update the "User" and "Meeting" models to establish the associations between them:
In the "User" model, we have two "has_many" associations with the "Meeting" model. The "has_many :sent_meetings" and "has_many :received_meetings" They both point to the class name of "Meeting" and have unique foreign keys.
In the "Meeting" model, it has two "belongs_to" associations with the "User" model. We used the "class_name" option to specify the name of the associated model, and specified it to use the same foreign key that associates with it from the "User" model.
Now you can create and retrieve meetings between users. With each Meeting having two foreign keys from the "User" model you can now call "user.received_meetings" or "user.sent_meetings" to retrieve the associated data. As always still a student so I am still learning but hopefully this has been helpful.
Top comments (0)