Verifying Active Record Associations
Tags: rails, ruby
Published: 2020-09-26 22:48:26

This blog is a brief overview of Active Record Associations and how to confirm your associations are working properly. 

## What is Rails?
> Rails is a web application development framework written in the Ruby programming language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks. [https://guides.rubyonrails.org/getting_started.html]

Web frameworks provide structure in our applications and allow us to focus on features rather than configuration details. 

## What are Active Record Associations?
To understand associations, we must first look at Active Record.
### Active Record 
> Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. https://guides.rubyonrails.org/active_record_basics.html

Active Records objects are hashes with key-value pairs that will be saved to a database.

Below is an example of how a User model is generated.

```
rails g resource user name:string age:integer
```

We may see the data (key-value pairs) that is stored by looked at our schema file

```ruby
# ../db/schema.rb

create_table "users", force: :cascade do |t|
    t.string "name"
    t.integer "age"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
```

Now we can create users with a name and an age. We do this by entering our rails console.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7qek7rzqbhc7a9fhtmua.png)

As shown above, we now have a user instance with the name of string "Pharia" and the age of integer 27. 

**However**, what if need to store the user's pets?

We could have a key of "pet" with a string of the animal's name.

```ruby
create_table "users", force: :cascade do |t|
    t.string "name"
    t.integer "age"
    t.string "pet" # new key to store pet
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
```
**BUT**, this would not account for if a pet has attributes of its own.

Additionally, what if a user has multiple pets?

This is where Active Record Associations comes along.

### Active Record Associations
> In Rails, an association is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code.
https://guides.rubyonrails.org/association_basics.html

Instead of adding a pet attribute to our User model. We instead generate a new Active Record model of Pet.

```
rails g resource pet name:string sex:string user_id:integer
```

The important key in this model is the **user_id**, because that is how we will know what user a pet belongs to. It is the _foreign key_.

```ruby
create_table "pets", force: :cascade do |t|
    t.string "name"
    t.string "sex"
    t.integer "user_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
```

We now update our models to account for this relationship.

```ruby
class User < ApplicationRecord
    has_many :pets
end
```

```ruby
class Pet < ApplicationRecord
    belongs_to :user
end
```

### Verifying Associations

When you declare associations, the declaring classes gain methods related to the association. 

First, to confirm our associations are working, we will utilize the _collection.build(attributes = {})_ method.

**collection.build(attributes = {}) method**

To confirm the association is working:
1. Target our user and assign to **variable u**
2. Instantiate a new instance of pet belonging to user by **u.pets.build(name: "Teddy", sex: "male")**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kglfz5gye2vj0814ns3c.png)

3. Save the user object once more
4. Access association **(u.pets)** and confirm array includes new pet object

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/sqak092oj8rnk8prbhru.png)

Second, we will utilize the _association_ method.

**association method**

1. Target our pet and assign to **variable p**
2. Confirm user that pet belongs to by **p.user**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/l6qd6dbqe5o6ajx7cvtf.png)

Methods are returning the correct data. Associations work!

## Conclusion

When confirming Active Record Associations, use the built-in methods such as **association.build(attributes = {})** & **association** to confirm that object relationships are returning as expected.

& Remember... Happy coding, friends! =)