jamby
jamby

Reputation: 606

Keeping validation errors after redirect from partial back to the same page that has the partial

So I'm trying to get the errors from my form that is rendered as a partial inside my root_path. After I attempt to post it, and it fails (or succeeds), I want to redirect back to the root_path. However, redirect_to decides to not save any information for the validation.

Wondering how to do this.

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @nom = current_user.noms.build(params[:nom])
    if @nom.save
      flash[:success] = "Nom created!"
      redirect_to root_path
    else
      flash[:error] = @nom.errors
      redirect_to root_path
  end

In my Home/Index, I render the partial for the form of the post.

= form_for [current_user, @post] do |f|
  = f.text_field :name
  = f.select :category
  = f.text_area :description
  = f.submit "Post", class: "btn btn-primary"

  - @post.errors.full_messages.each do |msg|
    %p
      = msg

It should be keeping the errors at the bottom of the form after it redirects to the root_path.

I'd also like to keep the information that was there after the validation failed.

Upvotes: 5

Views: 6371

Answers (3)

Piyush Chaudhary
Piyush Chaudhary

Reputation: 313

You can not use redirect_to for showing the error messages of an object because while redirecting it discards your object which does have linked with the error_messages & took a new object to redirect the path.

So in that case, you only have to use render.

respond_to do |format|
        format.html { 
          flash[:error] = @account.errors.full_messages.join(', ')
          render "edit", :id => @account._id, sid: @account.site._id
        }
end

Upvotes: -1

Dobler
Dobler

Reputation: 829

This seemed to work for me

format.html { redirect_to :back, flash: {:errors => "Document "+@requested_doc.errors.messages[:document][0] }}

I don't know if this could cause any other exception issues.

Upvotes: 1

ole
ole

Reputation: 5233

You should not use redirect in this case, instead use render:

class PostsController < ApplicationController
  #..

  def create
    @nom = current_user.noms.build(params[:nom])
    if @nom.save
      flash[:success] = "Nom created!"
      redirect_to root_path
    else
      flash[:error] = @nom.errors
      render :template => "controller/index"
    end
  end

Replace controller/index with names of you controller and action

Also check this question

Upvotes: 5

Related Questions