DEV Community

Cover image for Associations in Rails
rwparrish
rwparrish

Posted on

Associations in Rails

In this blog, I want to take a quick look at a very simple thing we can do to verify our associations have been set up properly at the start of a Rails project using some ActiveRecord magic.

Once you have an idea of what your database table relationships will look like and have them defined in your project, it's a great idea to quickly create some dummy data in the rails console to verify your associations are working how you want them to.

I was building an exercise journal and my relationships were as follows:

class Workout < ApplicationRecord
...
has_many :exercises
has_many :users, through: :exercises
...

class User < ApplicationRecord
...
has_many :workouts, through: :exercises
has_many :exercises
...

class Exercise < ApplicationRecord
...
belongs_to :workout
belongs_to :user
...
Enter fullscreen mode Exit fullscreen mode

We will be verifying these associations. So we head into the terminal and play in the Rails console rails c to create a couple of users:

c = User.create(name: "Stan", email: "stan@stan.com", password: "password")
Enter fullscreen mode Exit fullscreen mode

c is arbitrary here and is used to call the newly created user, if we do this we can confirm that the new user has been assigned a user_id of 1, meaning it was successfully saved to the DB. We should be able to see the attributes that were passed in as well (name, email, password). Repeat the process to create a second user which should save with a user_id of 2. Great! We’ve got our users.

Now on to workouts. It’s important to create the users and workouts first, given that our joins table is the exercises table. This is because each exercise created will need to be associated with a user and a workout - the exercises table will "join" the users and workouts tables. You can see this in the relationships code snippet provided above.

c = Workout.create(name: "HIT", notes: "No rest")
Very similar to the users example. This should save with a workout_id of 1. You can confirm this by calling c in the terminal. Make one more workout and then it’s time to create some exercises:

c = Exercise.create(name: "Burpee", user_id: 1, workout_id: 1)
Above I assigned foreign keys to the exercise object and then checked to see if it saved to the DB by calling c in the terminal.

c = Exercise.create(name: "Pushup", user_id: 2, workout_id: 1)
c = Exercise.create(name: "Situp", user_id: 1, workout_id: 2)
Enter fullscreen mode Exit fullscreen mode

Now we can call User.all.first.workouts or User.all.last.exercises or Workout.all.last.exercises for example.

I hope this helps you get started. It’s important to verify these relationships are working correctly before getting too deep into your project.

Happy coding!

Top comments (0)