Rails 6.0.3.4
I stumbled while implementing error handling for the comment feature, so I'll record it here.
I am making a recipe posting site, and when I enter the details of the recipe, there is a comment function and a comment list in it. The name of the user who posted the comment is also included. Comment It is assumed that the view that displays the model controller comment is completed. In routing, Comments are nested in Recipe.
class Comment < ApplicationRecord
belongs_to :recipe
belongs_to :user
validates :contents, presence: true, length: { maximum: 100 }
end
It looks like this. contents is the column name that contains the comment content. The validation of contents is that you cannot post in the blank and that it is 100 characters or less.
class CommentsController < ApplicationController
def create
@recipe = Recipe.find(params[:recipe_id]) #Define which recipe is associated
@comment = Comment.new(comment_params) #Create an empty instance (don't forget the strong parameters)
if @comment.save #If you can save the comment
redirect_to recipe_path(@comment.recipe.id) #You will be returned to the recipe list. Let's tell which recipe id is in the return path. Because we are [email protected] with id
else #If you can't save it (when it's validated)
@comments = @recipe.comments.includes(:user) #For comments, display the comments so far (I did not write here)
render 'recipes/show' #Return to the recipe list
end
end
private
def comment_params
Abbreviation
end
end
For the time being, if it is not saved, just render it back! I wrote only render. However, when I do so, an error message appears, but an error occurs in which the comments so far disappear from the list.
render is to display the view directly in the first place. It does not go through the controller. In other words, it goes to render'recipes / show' without defining @comments, so What is @comments written in the recipe list (recipes / show view)? It seems that it was. So let's define @comments before returning to the view with render.
I'll set it aside just in case.
<div class="comment-box">
<% if @comments %>
<% @comments.each do |comment| %>← Here@comments
<p>
<strong><%= comment.user.nickname %>:</strong>
<%= comment.contents %>
</p>
<% end %>
<% end %>
</div>
Recommended Posts