Griunvald
Griunvald

Reputation: 11

How to display error messages for nested form using simple_form gem

I created blog with ability create comments using rails 5.1.2 and simle_form 4.0.0. App has two forms - first for creating blog post, second for creating comments. Comments form nested in post show page. Validation for both forms work properly, but problem that comment form not display error messages. How to achieve that?

Post model: app/models/post.rb

class Post < ApplicationRecord
  has_many :comments, dependent: :destroy
end

Comment model: app/models/comment.rb

class Comment < ApplicationRecord
  belongs_to :post
  validates :comment_content, presence: true, length: { maximum: 5000 }
end

Comments controller: app/controllers/comments_controller.rb

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment].permit(:comment_content))
    redirect_to post_path(@post)
  end
end

Comment form: app/views/comments/_form.html.erb

<%= simple_form_for([@post, @post.comments.build]) do |f| %>
  <%= f.input :comment_content, input_html: { class: 'texture' }, wrapper: false, label_html: { class: 'label'
  } %>

  <%= f.button :submit, 'Leave a reply', class: "btn btn-primary" %>
<% end %>

Comment partial: app/views/comments/_comment.html.erb

<%= comment.comment_content %>

Post show page, where comment form rendered: app/views/posts/show.html.erb

<p id="notice"><%= notice %></p>

<p>
  <!-- Post details -->
</p>

<%= render @post.comments %>

<%= render 'comments/form' %>

Routes:

Rails.application.routes.draw do
  resources :posts do
    resources :comments
  end
end

Upvotes: 1

Views: 1165

Answers (1)

Vasilisa
Vasilisa

Reputation: 4640

At first you need to add

<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

to the comments form for errors rendering.

Also you need to change create action in the CommentsController - it should rerender form on validation fail.

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment].permit(:comment_content))
  if @comment.save
    redirect_to post_path(@post), notice: 'Comment was successfully created.'
  else
    render 'posts/show'
  end
end

Upvotes: 0

Related Questions