Second Model

y'all in a real relationship...?

·

2 min read

Hello.

rails g model Comment body:string references:post
# references to :post implies relationship between both tables :posts and :comments

We created a new model comment with references to post.

# app/models/comment.rb

class Comment < ApplicationRecord 

  belongs_to :post
  # implies that an instance of Comment belongs to one instance of Post
end

Likewise in Post model:

# app/models/post.rb

class Post < ApplicationRecord

  has_many :comments
  # implies that each instance of Post may have many instances of Comment
end

The above migration while creating the model Comment would be something like this:

class CreateComments < ActiveRecord::Migration[7.0]
  def change
    # ...
    add_reference :posts, :comment, foreign_key: true

    # the first symbol [:posts] refers to the table we are changing
    # the second [:comment] refers to the table we are forming a relation with
    # "foreign_key :true" simply means the table :comments will employ a foreign_key :post_id that refers 
    # to the primary_key :id of :posts table
  end
end

Learn more about it below:

  1. Active Record Associations
  2. Active Record Migrations

As you can imagine, comments can have the same :post_id which would mean that the Post(:post_id) have the said comments.

We can simply retrieve a post's comments by a really intuitive simple query:

@post = Post.find(:id)
@post.comments
# Returns all the comment objects that belongs to the Post: @post

One of the reasons why I love Ruby and is called a Programmer's best friend is how intuitive, simple and straight-forward it is.

Cutting it short today. See y'all later.

In the next article, we shall discuss about Ruby version managers .rbenv and .rvm.

See ya!

Love,

M.

liked_the_post == true ? comment and share : comment and share