[RUBY] I want to add a delete function to the comment function

【Overview】

1. Conclusion </ b>

2. How did you implement it? </ B>

3. What I want to do in the future </ b>

  1. Conclusion

❶ Make it possible to link the posted id to the destroy action of the comment controller and delete it.

❷ Allow the delete button to be pressed with link_to on the nested path.


2. How did you implement it?

<Development environment>
Ruby: 2.6.5
Rails: 6.0.3.3

controllers/comments_controller.rb


  def destroy
    redirect_to root_path unless user_signed_in? || current_user.id == @time.user_id && current_user.id == comment.user_id #---(1)
    @comment = Comment.find(params[:time_id])
    if @comment.destroy  #---(2)
      redirect_to time_path #---(3)
    else
      redirect_to root_path #---(4)
    end
  end

❶ The posted id can be linked to the destroy action of the comment controller and deleted. In (1), this is to prevent people who are logged out and posters other than yourself from deleting comments on their posts (directly entering the URL to delete them). (2) deletes the comment you posted. If (3) is successful, you will be returned to the comment posting screen. (4) will return to the top page if the comment deletion fails.

ruby:view/time/show.html.erb


      <% if @comments %>#---(1)
        <% @comments.each do |comment| %>#---(2)
          <p>
           <%= comment.user.name %>:#---(3)
            <% if user_signed_in? && current_user.id == @time_report.user_id && current_user.id == comment.user_id %>
              <%= link_to '❌', time_report_comment_path(comment.id), method: :delete %> #---(4)
               <%= comment.content %> #---(5)
            <% end %>
           </p>
        <% end %>
      <% end %>

❷ The delete button can be pressed with link_to on the nested path. (1) is "if there is a comment", so it is an instance variable and is brought from the time controller. (2) User ➡︎ comments is has_many, so I bring a lot of comments. (3) Among them, only the linked user name of the comment is displayed. (4) Since the comments are nested by routing, you can delete your own comments posted by yourself. </ b> (5) The content of the comment is displayed.


  1. What I want to do in the future

I want to implement a SPA. When I click the balloon mark, the comment is displayed asynchronously (without page transition), and I want to make the application so that I can edit or delete it. For that, knowledge of Nuxt.js / Vue.js is required, so I will study it steadily.

Recommended Posts