Now that we have created the Memo model, we are going to associate it with a User.
A User can have many Memos and but a Memo belongs to only one User.
Lets look at how that looks like in the Entity Relation Diagram for our app.
Rails uses ActiveRecord to manage the relationship between the Model and the database.
To create a relationship between the User and Memo we are going to have to create a few migrations.
Run the following in terminal:
rails generate migration AddUserToMemos user:references
We created a manual migration file when creating Users.
The difference with this migration is that we specify the relationship directly to the generator.
Rails infers the Model that the relationship is going to be attached to (Memo) from the AddUserToMemos
The last parameter user:references is attaching the User model as a relationship to Memo.
class AddUserToMemos < ActiveRecord::Migration[5.1]
add_reference :memos, :user, foreign_key: true
Make sure to run rails db:migrate after creating the migration file
Adding Associations to the Models
Types of Rails Associations
There are many types of associations in Rails:
- has_many :through
- has_one :through
We are going to be using the belongsto_ and the hasmany_ in this tutorial.
When creating relationships think about who needs to hold the foreignkey to a table.
In this tutorial every Memo will need to reference an existing user in our database and hence holds a foreignkey to the users table.
A belongs_to association sets up a one-to-one connection with another model. When we use a belongs to association, we indicate that we (the Memo model in this example) contains the foreign key to another model.
A has_many association indicates a one-to-many connection with another model. This doesn't use any foreign keys. It simply lets Rails know that there is another model that holds the a foreign key to itself.
Keeps these associations in mind as we will be using these them in the next section.
Adding Users to Memo
Add the following to your Memo.rb file:
Your Memo.rb file should look like this now:
class Memo < ApplicationRecord
Adding Memos to User
Add the following to your user.rb file:
Your user.rb file should look like this now:
class User < ApplicationRecord
Testing our relationships in the rails console
To test our relationships we will create a User and Memo model in the rails console.
user = User.create(
Save the user
memo = Memo.create(
title: "My Memo",
text_body: "Memo text body",
Save the memo
If the relationships were setup properly, you should be able to save both the user and the memo.
- To create associations in Rails, we first have to create a migration file to add the association to our database then we need to modify the models with the association keywords (eg. belongsto, hasone).
If you have feedback on this tutorial or find any mistakes, please open issues on the
GitHub Repository or comment below.