Ruby on Rails CRUD Associations App

Nancy Do
2 min readAug 15, 2018

--

Table of Contents

In my previous blog, we built a simple Rails web application that accomplished all of the CRUD operations. Let’s dive a little deeper and add associations to our application to make it more useful for real-world projects.

In this tutorial, we’re going to build an application where we’re able to assign 1 or more dogs to each owner. This is known to be a one-to-many relationship.

[include one-to-many relationship pic]

Let’s start with what we’re most familiar with and build out the model and controller for the owners first since it doesn’t have any dependencies.

Model/Controller Setup

  1. Create a new Rails application (-T to create without the test framework):
rails new friends-with-dogs-app -T

2. Change your directory to access the application:

cd friends-with-dogs-app/

3. Generate the owner model for the application (model should be singular):

rails g model owner first_name last_name occupation age:integer img_url

4. Generate the owners controller for the application (controller should be plural):

rails g controller owners index show new edit

5. Generate the dog model for the application:

rails g model dog name breed age:integer owner:belongs_to

Note: Setting belongs_to on the owner when you generate the model will update the Dog class in our models/dog.rb file with the following:

ActiveRecord knows to associate the dog with its owner.

6. Let’s make sure our models/owner.rb is set up correctly:

7. Generate the dogs controller for the application:

rails g controller dogs index show new edit

8. Update the config/routes.rb file to include all routes:

9. Run rake db:migrate to create the owners and dogs tables in our database based on our migration files:

db/migrate/[datetime]_create_owners.rb
db/migrate/[datetime]_create_dogs.rb

10. Update the db/migrate/seeds.rb file to add owners and dogs to our database:

Run rake db:seed .

11. Runrails c and make sure if your data has been seeded correctly.

12. Follow steps 9–15 in the Simple CRUD Tutorial and try to build out the CRUD functionality for owners.

13. Notice that we are storing the owner’s first and last name separately. We wouldn’t want to concatenate that on each of our view files because that would defeat the purpose of DRY. Let’s create a method and just call that each time we need to:

models/owner.rb

Owner Setup

owners_controller.rb

Owner — controller.rb
Owner — index.erb
Owner — show.erb
Owner — new.erb
Owner — edit.erb

Dogs Setup

dogs_controller.rb

Dog — controller
Dog — index.erb
Dog — show.erb
Dog — new.erb
Dog — edit.erb

Full Demo

Enjoy!

--

--