Friday, February 11, 2011

RoR: Creating/Updating: Showing validation errors while preserving previous values

I have a basic model in which i have specified some of the fields to validate the presence of. in the create action in the controller i do the standard:

@obj = SomeObject.new(params[:some_obj])

if @obj.save
  flash[:notice] = "ok"
  redirect...
else
  flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "<br/>" }
  redirect to new form
end

however when i redirect to the new form, the errors show, but the fields are empty. is there a way to repopulate the fields with the entered values so the errors can be corrected easily?

  • You render :action => :new rather than redirecting.

    Ian Terrell : The reason behind this is so that you keep the object in memory rather than creating a new object; the redirect starts an entirely new request.
    James A. Rosen : The downside is that the form for creating a SomeObject now has two URLs: /some_objects/new # for the first form /some_objects # after a failed POST Not much can be done about it, though.
    Ryan Bigg : Good points Ian & Gauis
    From Ryan Bigg
  • Capture @obj in the flash hash as well, and then check for it in the new action.

    @obj = SomeObject.new(params[:some_obj])
    
    if @obj.save
      flash[:notice] = "ok"
      # success
    else
      flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "<br/>" }
      flash[:obj] = @obj
      # redirect to new form
    end
    

    In new:

    @obj = flash[:obj] || MyClass.new
    
    From nertzy

0 comments:

Post a Comment