Setting up Database Associations in Rails
Learn how to configure database relationships between models in a Ruby on Rails application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In the last lesson, we setup our Task model, and in this lesson, we are going to wire it with our project file. So, go to project.rb and type the code

has_many :tasks

large

To confirm that this worked, let's start our rails console and see what's the last record with the code Project.last. This will bring up the last record with a project_id of 21. Now, to test the task method run the following commands in the console:

Task.create! (title: "My first task", description: "asdf", project_id=21)

This command will create a task record into the database. You can try one more if you like

Task.create! (title: "My second task", description: "asdf", project_id=21)

and this will be inserted into the database as well.

large

To check if all of this worked, type Project.last.tasks and this will bring up the last task record. You can also check the number of tasks with the query Project.last.tasks.count and this will return the value 2.

large

It's also possible to query the project associated with the last task, and to do this, type Task.last.project and this will bring up the record with project_id of 21.

This association is important to know as the task.rb file has belongs_to :project while the project.rb file has the code has_many :tasks. This two-way association makes it possible for us to access the project object through tasks and vice-versa.