I summarized the implementation of the comment function in rails.
The development environment for Ruby on Rails is in place. Posts (post table) and User (user table) have already been created. The User table uses gem devise. This time we will implement a comment for the post.
The details and relations of the Comments table to be created are as follows.
$ rails g model comment
20********_create_comments.rb
class CreateComments < ActiveRecord::Migration[6.0]
def change
create_table :comments do |t |
#Described from here
t.references :user,foreign_key: true
t.references :post, foreign_key: true
t.text :text,nul: false
#Described so far
t.timestamps
end
end
end
$ rails db:migrate
app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
app/models/user.rb
class User < ApplicationRecord
has_many :posts
has_many :comments
end
app/models/post.rb
class Comment < ApplicationRecord
has_many :users
has_many :comments
end
routes.rb
Rails.application.routes.draw do
resources :users
resources :posts do
resource :comments
end
end
comments_controller.rb
class CommentsController < ApplicationController
def create
@comment = Comment.create(comment_params)
redirect_back(fallback_location: root_path)
end
private
def comment_params
params.require(:comment).permit(:text).merge(user_id: current_user.id, post_id: params[:post_id])
end
end
posts_controller.rb
class PostsController < ApplicationController
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to user_url(current_user)
else
render :new
end
end
def show
#Write comment instance creation
#This time Posts#I would like to implement a comment function in show.
@comment = Comment.new
@comments = @post.comment_cs.includes(:user)
end
private
def post_params
params.require(:post).permit(:text).merge(user_id: current_user.id)
end
def set_post
@post = Post.find(params[:id])
end
end
erb:views/posts/show.html.erb
#abridgement
<%= form_with model: [@post,@comment],merhod: :post,locals: true do | form | %>
<%= form.text_area :text %>
<%= form.submit "Post" %>
<% end %>
#abridgement
Comment function completed!
This time, I started the comment function in Rails from table creation. I am also a beginner in programming, so please let me know if you make any mistakes. Thank you for reading until the end!
Recommended Posts