Christian Fazzini
Christian Fazzini

Reputation: 19713

How to render validation errors on the page that submitted the form?

I've got a comments form in the article/show page. In this page, it displays the article and has a comments form.

When I submit a comment that has validation errors, I need it to go back to the article/show page, and display the errors there.

Should I change render :action => 'new' to something else?

In the Comment controller, I tried:

  def create
    ...

    if @comment.save?
      redirect_to article_path(@comment.article), :notice => "Posted comment!"
    else
      # render :action => 'new'
      render 'articles/show"
    end
  end

But this will complain, since the app won't know which article to show based on the ID.

EDIT: I found this solution. The approach would be to use a session to pass the errors instead. Is this the right way to go with this?

Upvotes: 2

Views: 3403

Answers (2)

Pravin
Pravin

Reputation: 6662

Try this

def create
    ...

    if @comment.save?
      redirect_to article_path(@comment.article), :notice => "Posted comment!"
    else
      # render :action => 'new'
      @article = @comment.article
      render 'articles/show"
    end
  end`

Upvotes: 4

sevenseacat
sevenseacat

Reputation: 25029

So fix your routing so the app does know what article to show based on the ID.

Upvotes: 0

Related Questions