[Rails] How to display error messages for comment function (for beginners)

Introduction

This article is the first step for a fledgling engineer! This is an article of AdventCalendar2020 Day 19.

Application overview

This is a general application that allows you to comment on user posts. (Use devise for user registration) Currently, we have not set validation for comment, so it is possible to post blank.

ER diagram

_2020-12-15_12.07.40.png

Comment function

The view and controller of the comment function before implementation are as follows.

ruby:post_images/show.html.erb * Excerpt from the comment posting part only


<%= form_with model:[@post_image, @comment], local:true do |f| %>
  <div class="row">
    <div class="col-sm-12">
       <%= f.text_area :comment, rows:'5', class: "form-control",placeholder: "Comment here" %>
    </div>
  </div>
   <%= f.submit "Send", class: "btn btn-lg btn-base-1 mt-20 pull-right" %>
<% end %>

post_images/controller.rb


def show
    @post_image = PostImage.find(params[:id])
    @comment = Comment.new
end

comments/controller.rb


def create
   post_image = PostImage.find(params[:post_image_id])
   comment = current_user.comments.new(comment_params)
   comment.post_image_id = post_image.id
   comment.save
   redirect_to post_image_path(post_image)
end

private
def comment_params
  params.require(:comment).permit(:comment)
end

Add an error message to the comment function

1. Comment model validation settings

models/comments.rb


validates :comment, presence: true

2. Conditionally branch the controller

If the save of the local variable comment fails, the comment is known to contain the error content. In order to reflect the status in view (display an error message), it is necessary to redefine the comment containing the error content in the instance variable @error_comment.

comments/controller.rb


def create
    post_image = PostImage.find(params[:post_image_id])
    comment = current_user.post_comments.new(comment_params)
    comment.post_image_id = post_image.id

   #6 lines added (if ~ end)--------------------------------
    if comment.save
	    redirect_to post_image_path(post_image)
	else
		@error_comment = comment
		render 'post_image/show'
	end
   #-----------------------------------------------
end

private
def comment_params
  params.require(:comment).permit(:comment)
end

3. Describe the display of the error message

Pass the @error_comment you just redefined to view.

html:post_images/show.html.erb * Excerpt from the comment posting part only


<%= form_with model:[@post_image, @post_comment], local:true do |f| %>

----Added display of error messages------------------------------------------------
  <% if @error_comment.present? %>
    <div id="error_explanation">
      <h2><%= @error_comment.errors.count %>An error has occurred.</h2>
      <ul>
        <% @error_comment.errors.full_messages.each do |message| %>
        <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
--------------------------------------------------------------------------

  <div class="row">
    <div class="col-sm-12">
      <%= f.text_area :comment, rows:'5', class: "form-control",placeholder: "Comment here" %>
    </div>
  </div>
  <%= f.submit "Send", class: "btn btn-lg btn-base-1 mt-20 pull-right" %>
  <% end %>

Display only when there is an error in <% if @ error_comment.present?%> On the second line. @Error_comment is not defined when displaying the show page because it is a variable that is redefined only when comment is an empty post. Without <% if @ error_comment.present?%>, The following error will occur. _2020-12-15_15.06.32.png

4. Add the contents of the show action of post_image to the create action

If the comment posting fails, it is rendered to the show page of post_image, but the instance variable required to display the view of the show is not in the create action of the comment controller, so it is necessary to add it.

post_images/controller.rb


def show
    @post_image = PostImage.find(params[:id])
    @post_comment = PostComment.new
end

Append.

comments/controller.rb


def create
    post_image = PostImage.find(params[:post_image_id])
    comment = current_user.post_comments.new(post_comment_params)
    comment.post_image_id = post_image.id
    if comment.save
	    redirect_to post_image_path(post_image)
	else
		@error_comment = comment

#------post_Added show action for image---------------
		@post_image = PostImage.find(params[:id])
	    @post_comment = PostComment.new
#-------------------------------------------------
		render 'post_image/show'
	end
end

private
def comment_params
  params.require(:comment).permit(:comment)
end

Now when I post a comment, I get the following message saying that I can't find it because I don't have an id. To be exact, there is an id, but the name has changed and it is different, so it feels like I can not find the id. _2020-12-15_15.19.57.png If you check with rails routes,

Prefix Verb URI Pattern Controller#Action
post_image GET /post_images/:id(.:format) post_image#show
post_image_comments POST /post_images/:post_image_id/comments(.:format) comment#create

In the show action, the parameter id of post_images was: id, but in the case of create action, the parameter id is post_image_id. Therefore, change the parameter id to post_image_id.

comments/controller.rb


def create
    post_image = PostImage.find(params[:post_image_id])
    comment = current_user.post_comments.new(post_comment_params)
    comment.post_image_id = post_image.id
    if comment.save
	    redirect_to post_image_path(post_image)
	else
		@error_comment = comment
 #----------Change(:id → :post_image_id)------------------------
		@post_image = PostImage.find(params[:post_image_id])
 #------------------------------------------------------------
	    @post_comment = PostComment.new
		render 'post_image/show'
	end
end

private
def comment_params
  params.require(:comment).permit(:comment)
end

_2020-12-15_15.37.08.png

Summary

It was a very roundabout explanation, but I hope it will be helpful for beginners who are having trouble solving errors.

Recommended Posts

[Rails] How to display error messages for comment function (for beginners)
[Rails] How to display error messages individually
[Ruby on Rails] How to display error messages
Rails [For beginners] Implementation of comment function
How to display error messages in Japanese
[For beginners] How to implement the delete function
[Rails] How to get success and error messages
[Rails] How to use flash messages
[rails] How to display db information
How to resolve Missing Template error when implementing comment function
[Rails] Display form error messages asynchronously
[Rails] Comment function (registration / display / deletion)
[RSpec on Rails] How to write test code for beginners by beginners
Ruby on Rails for beginners! !! Post list / detailed display function summary
Testing for Error Messages: Rails Tutorial Notes-Chapter 7
[Ruby] How to use slice for beginners
[Rails] How to use video_tag to display videos
[For beginners] How to debug in Eclipse
How to build a Ruby on Rails environment using Docker (for Docker beginners)
How to display error messages and success messages when registering as a user
(For beginners) [Rails] Time saving tech! How to install and use slim
[For Rails beginners] Summary of how to use RSpec (get an overview)
[Rails] Add page nation to table [For beginners]
The road to Japaneseizing Rails devise error messages
[Rails] How to implement unit tests for models
[Rails] How to use Gem'rails-i18n' for Japanese support
[Rails] How to solve "Uglifier :: Error: Unexpected character'`'"
How to make a follow function in Rails
[Rails] How to convert UC time display to Japanese time display
[Ruby on Rails] Individual display of error messages
[Rails] How to easily introduce slick (slider function)
How to write Rails
How to uninstall Rails
[Rails] How to create a signed URL for CloudFront
[Rails, JS] How to implement asynchronous display of comments
Rails / Ruby: How to get HTML text for Mail
[For beginners] How to operate Stream API after Java 8
[Spring Boot] How to create a project (for beginners)
[For Rails beginners] Implemented multiple search function without Gem
[For beginners] Minimum sample to display RecyclerView in Java
[Rails] validates How to translate error sentences into Japanese
Rails learning How to implement search function using ActiveModel
[RSpec] How to test error messages set by Shoulda-Matchers
[Rails] How to display an image in the view
How to use GitHub for super beginners (team development)
[Ruby on Rails] How to implement tagging / incremental search function for posts (without gem)
Explanation of Ruby on rails for beginners ④ ~ Naming convention and how to use form_Tag ~
[rails] How to post images
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
Tutorial to create a blog with Rails for beginners Part 1
How to add ActionText function
[Rails] How to use enum
[Rails] Workaround for classes automatically generated by devise error messages
[Rails] How to install devise
[Rails] How to use enum
How to leave a comment
How to read rails routes
[For Ruby beginners] Explain how to freely delete array elements!
From Ruby on Rails error message display to Japanese localization
(For beginners) [Rails] Install Devise
Display Flash messages in Rails