Verifying Active Record Associations

phariale

pharia-le

Posted on September 26, 2020

Verifying Active Record Associations

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

# ../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

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.

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.

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.

class User < ApplicationRecord
    has_many :pets
end
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

  1. Save the user object once more
  2. Access association (u.pets) and confirm array includes new pet object

Alt Text

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

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! =)

💖 💪 🙅 🚩
phariale
pharia-le

Posted on September 26, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related