ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
-Build login environment with devise -Posting function that only logged-in users can do -Post editing function (update, delete)
Terminal
$ rails g model Comment user:references post:references comment:string
Terminal
$ rails db:migrate
app/models/user.rb
has_many :comments, dependent: :destroy
app/models/post.rb
has_many :comments, dependent: :destroy
Terminal
$ rails g controller comments create destroy
app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(comment_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to request.referer
else
@post_new = Book.new
@comments = @post.comments
redirect_to new_post_path
end
end
def destroy
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to request.referer
end
private
def comment_params
params.require(:comment).permit(:comment)
end
end
app/controllers/posts_controller.rb
def show
@post = Post.find(params[:id])
@comment = Comment.new
@comments = @post.comments
end
config/routes.rb
resources :posts, except: [:index] do
resources :comments, only: [:create, :destroy]
end
erb:app/views/show.html.erb
<h1>Posts#show</h1>
<span>Currently logged in user:<%= current_user.name %></span>
<table>
<thead>
<tr>
<th>Posted by name</th>
<th>title</th>
<th>Text</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><%= @post.user.name %></td>
<td><%= @post.title %></td>
<td><%= @post.body %></td>
<td><%= link_to "Edit", edit_post_path(@post) %></td>
</tr>
</tbody>
</table>
<%= form_for [@post, @comment] do |f| %>
<%= f.text_area :comment, size: "40x5" %>
<%= f.submit 'Send', class: "btn-sm btn-primary" %>
<% end %>
<table>
<thead>
<tr>
<th>Comment contributor</th>
<th>Comment content</th>
</tr>
</thead>
<tbody>
<% @comments.each do |comment| %>
<tr>
<td><%= comment.user.name %></td>
<td><%= comment.comment %></td>
<td><%= link_to "Delete", post_comment_path(@post, comment), method: :delete %></td>
</tr>
<% end %>
</tbody>
</table>
erb:app/views/new.html.erb
<table>
<thead>
<tr>
<th>Posted by name</th>
<th>title</th>
<th>Text</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @posts.each do |post| %>
<tr>
<td><%= post.user.name %></td>
<td><%= post.title %></td>
<td><%= post.body %></td>
<td><%= link_to "Details", post_path(post) %></td>
<td><%= link_to "Edit", edit_post_path(post) %></td>
<td><%= link_to "Delete", post_path(post), method: :delete %></td>
</tr>
<% end %>
</tbody>
</table>
Goal completed.
Recommended Posts