1

I'm using Rails 4 and Chrome. The following results in the situation:

  1. Post a form that causes a validation error (ie. "Name cannot be empty")
  2. Post that same form successfully by correcting the input
  3. Hit the browser back button and the validation error from step 1 is shown on the input field even though it has a value that is not empty

Why does the validation error from the step 1 pop back and how to fix this behaviour? Note: Turbolinks is in use, could that be the reason?

Here's the way to replicate:

rails g scaffold Page name:string

class Page < ActiveRecord::Base
  validates :name, presence: true
end
Navigate to /pages/new
Submit (errors appear on the form)
Fillout the name
Submit again (redirected to successfully created model)
Hit the browser back button (the validation errors are there, and the field is filled with the last supplied value)
randomguy
  • 12,042
  • 16
  • 71
  • 101

1 Answers1

1

I guess you are using something like the following code to send back the errors related to the record being created/updated:

def update
  @post = Post.find(params[:id])
  if @post.update_attributes(post_params)
    # your logic when successfull
  else
    render :edit, flash[:errors] = @post.errors
  end
end

Or something similar. My point here is that you should use the following syntax for setting the errors in the flash :

flash.now[:errors] = @post.errors

(1) This should set the flash[:errors] available only for the current page and delete it right after you leave this page.

(2) You could also use flash.clear at the end of your view, but this is not how it is supposed to be done, and seems a little bit "hacky".


Resources:

Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117