Dercni
Dercni

Reputation: 1224

Displaying validation errors for a nested form

I am working my way through Rails getting started guide:

http://guides.rubyonrails.org/getting_started.html

This guide creates and Articles model with a nested comments model. If validation fails when creating an article the new action is rendered and validation error messages can be displayed whilst preserving the user input.

http://guides.rubyonrails.org/getting_started.html#adding-a-second-model

My question is as the comments form is displayed by the articles#show action then in the comments controller what should be rendered when saving a comment fails? Normally I would simply render 'new' however this would related to the comments#new action which does not exist.

class CommentsController < ApplicationController
  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.new(comment_params)
    if @comment.save
      redirect_to article_path(@article)
    else
      render ????????
    end
  end

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

Upvotes: 1

Views: 108

Answers (1)

Kevin Etore
Kevin Etore

Reputation: 1144

Try to render the corresponding articles action. So something like render 'articles/new' or render template: 'articles/new' would function.

Upvotes: 1

Related Questions