0

In my controller, I want to handle an ActiveRecord::RecordInvalid exception by redirecting back to the controller action that caused the exception with a flash message, but I also would like to retain the form data that the user entered. Is there a best approach for dealing with this?

rescue_from ActiveRecord::RecordInvalid do |exception|
  redirect_to :back, alert: exception.message
end

This currently redirects and shows the flash message properly, but I'm not sure what the best practice is for retaining the form data. Thanks in advance.

Joey
  • 343
  • 2
  • 10

1 Answers1

0

Generally this is the way to handle exceptions in the controller. Say for a create action.

def create
  @your_inst_var = YourModel.new(your_instance_var_params)

  if @your_inst_var.save
    redirect_to your_inst_var_path, notice: 'Your Inst Var was successfully created.'
  else
    render action: 'new'
  end
end

*your_instance_var_params is defined as a private method to satisfy rails 4 strong params

toolz
  • 871
  • 6
  • 12
  • Thanks for your reply, but I'm not sure there is any exception being handled in your example. Can you clarify? – Joey Jan 08 '14 at 02:17
  • RecordInvalid is raised when you can't save a record to the database. My answer handles this exception by checking to see if the record saved. If it wasn't saved then you know you raised RecordInvalid in which case you render the action new. Read this http://stackoverflow.com/a/14976232/1429856 as it explains why rendering new will keep your params. – toolz Jan 08 '14 at 17:44
  • Perhaps .save raises and handles its own exception and returns false in the case there is an exception (.save! would actually expose the exception, correct?). – Joey Jan 09 '14 at 18:45