1. Introduction to Rails Relationship

In rails associations defines the relationship/connection between two Active Record models.

Why do we need associations between models? Because they make common operations simpler and easier in your code.

Lets take and example here between models User and Post. A user can create many posts and when a user is destroyed the posts belonging to user should also be destroyed.

Without association the models looks like below

class User < ApplicationRecord
end

class Post < ApplicationRecord
end

With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up users and posts:

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end

class Post < ApplicationRecord
  belongs_to :user
end

Now we can easily create the post

@post = @user.posts.create(photo:"test", description: "test")

Also when we destroy the user the associated posts get destroyed.

@user.destroy

Rails support 6 types of associations

We will be using the belongs_to and has_many associations only.

For more information we can take look at the link.

We will be using associations between the User, Post and Comment model.

Lesson list