Deploy apps to servers that you own and control.
Application monitoring that helps developers get it done.
Now that we have posts fully set up in our application, it's time to scaffold the comments resource, allowing users to add comments under any post.
Let's return to our application and run another Rails generator. This time, we will scaffold a Comment resource.
A comment has three key attributes:
Let’s generate this resource by running the following command:
bin/rails generate scaffold Comment post:belongs_to user:belongs_to 'body:text!'
As always, this command generates:
Let’s inspect the generated migration. This migration ensures:
Let’s run our migrations to apply these changes.
Now that the comments table is created, we can commit our changes.
Next, we need to define the relationships in our models.
Comment Model (Generated by Rails)
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
end
We also need to update the Post model to establish its relationship with comments:
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
end
Adding dependent: :destroy ensures that when a post is deleted, all its associated comments are also removed.
Similarly, we update the User model:
class User < ApplicationRecord
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
end
This ensures that when a user account is deleted, all their posts and comments are automatically removed.
Now that our comments resource is set up, we still need to customize it to fit the specific needs of Lorem News.