JoHksi
JoHksi

Reputation: 517

Rails way of doing error handling to creating a model

I am building a rails app. I have a model called Application.

In application_controller.rb, I have following function

def create
        @application = resource.applications.build(attribute: "value")

        if @application.save
           //how should i return response code 200?
        else
            //if @application.save is not run correctly, how do I re-run @application.save?
        end    
end

I have total two questions.

1) How do I return response code 200 if @application.save is correctly done?

2) If @application.save is not run correctly for some reason, how do I make sure that @application.save is run again to make sure that the @application is eventually saved?

Thanks

Upvotes: 1

Views: 80

Answers (2)

rohin-arka
rohin-arka

Reputation: 789

From rails 4 you can send head

head :ok, content_type: "text/html"

For more information you can visit the below link

"render :nothing => true" returns empty plaintext file?

If .save do not save data there will be some reason. Looping until it do not save might not be a good way.

you can check errors by .errors.messages

and if you want still to save skipping model validations then you can use @application.save(validate: false)

You cant skip errors from database side I think.

Upvotes: 1

siopao
siopao

Reputation: 318

  1. You can return response code 200 this way: render status: 200 or render status: :ok

  2. It isn't advisable to keep trying to save @application since that would be an infinite loop. If it doesn't save for some reason, then that something needs to be addressed with another post request that passes validations; not forcibly run until it will somehow save (which it probably won't anyway).

Upvotes: 0

Related Questions