Rails recover from invalid form?

371 views Asked by At

I have a Rails 2.3 application.

I currently have the following validations in my model:

validates_presence_of :jobno, :companyname

I have the following controller:

# POST /kases
# POST /kases.xml
  def create
    @company = Company.find(params[:kase][:company_id])
    @kase = @company.kases.create!(params[:kase])

    respond_to do |format|
        UserMailer.deliver_makeakase("EMAILADDRESS", "Highrise", @kase) if params[:sendtohighrise]
        UserMailer.deliver_makeakaseteam("EMAILADDRESS", "Highrise", @kase) if params[:notify_team_of_creation]
        @kase.delay.create_freeagent_project(current_user) if params[:send_to_freeagent]

        #flash[:notice] = 'Case was successfully created.'
        flash[:notice] = fading_flash_message("Case was successfully created.", 5)
    end  
        format.html { redirect_to(@kase) }
        format.xml  { render :xml => @kase, :status => :created, :location => @kase }
  end

So when you try and create a new record that doesn't contain either a jobno or companyname I correctly get the following error message:

ActiveRecord::RecordInvalid in KasesController#create
Validation failed: {{errors}}

I have read about the recover ability, but I am unsure how/where to use it. I have read a few documents regarding the ability to rescue the content of the form. I am trying to make the form remain in place - with the entered content - but show an error on the form.

One of the documents I have read is here http://apidock.com/rails/ActiveRecord/RecordInvalid

I don't want to log the error, simply inform the user what the problem was so they can try again.

Is this possible?

Thanks,

Danny

1

There are 1 answers

0
fl00r On BEST ANSWER
def create
  @company = Company.find(params[:kase][:company_id])
  @kase = @company.kases.new(params[:kase])

  if @kase.save
    UserMailer.deliver_makeakase("EMAILADDRESS", "Highrise", @kase) if params[:sendtohighrise]
    UserMailer.deliver_makeakaseteam("EMAILADDRESS", "Highrise", @kase) if params[:notify_team_of_creation]
    @kase.delay.create_freeagent_project(current_user) if params[:send_to_freeagent]
    redirect_to @kase
  else  
    render :new
  end
end