Pedro Gabriel Lima
Pedro Gabriel Lima

Reputation: 1172

Rails ajax call 500 internal server error

I'm having trouble working with respond_to method: when the model got saved, it returns in json format correctly. But, when the model didn't get saved, because a error like ActiveRecord::RecordNotUnique, rails returns another respond that it's not my: "Completed 500 Internal Server Error" and the respond returned goes to ajax error fuction.

My question here is, how can I send the correct respond, the one inside the else statement, so I can show to users the correct errors messages.

I'm in development mode.

I change the code a little just for simplicity.

Thanks.

Controller:

def create 
  @distribuicao = DistribuicaoPorCargo.new(distribuicao_por_cargo_params)
  respond_to do |format|
    if @distribuicao.save
      format.json { render json: @distribuicao.distribuicao, status: :created }
    else
      format.json { render json: @distribuicao.errors.full_messages, status: :unprocessable_entity }
    end
  end
end

.js:

$.ajax 
    url: '/distribuicao_por_cargos'
    type: 'POST'
    dataType: 'JSON'
    data: {
      data: JSON.stringify(data_send_to_server)
    }
    success: (data, textStatus, jqXHR) ->
      console.log("AJAX Sucesss: #{textStatus}")
    error: (jqXHR, textStatus, errorThrown) ->
      console.log("AJAX Failed: #{textStatus}")

log:

Started POST "/distribuicao_por_cargos" for 187.110.216.111 at 017-06-02 17:32:22 -0300
Cannot render console from 187.110.216.111! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by DistribuicaoPorCargosController#create as JSON
Parameters: {"concurso_id"=>"2", "local_da_prova_id"=>"6", "tabela"=>"{\"cargo_id\":\"4\",\"quantidade_de_candidatos\":\"10\"},{\"cargo_id\":\"9\",\"quantidade_de_candidatos\":\"10\"},{\"cargo_id\":\"12}]"}
Concurso Load (0.4ms)  SELECT  "concursos".* FROM "concursos" WHERE "concursos"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
LocalDaProva Load (0.2ms)  SELECT  "local_da_provas".* FROM "local_da_provas" WHERE "local_da_provas"."id" = $1 LIMIT $2  [["id", 6], ["LIMIT", 1]]
(0.1ms)  
BEGIN 
LocalDaProva Load (0.3ms)  SELECT  "local_da_provas".* FROM   "local_da_provas" WHERE "local_da_provas"."id" = $1 LIMIT $2  [["id", 6], ["LIMIT", 1]] SQL (1.5ms)  
INSERT INTO "distribuicao_por_cargos" ("created_at", "updated_at", "local_da_prova_id", "distribuicao") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", 2017-06-02 20:32:23 UTC], ["updated_at", 2017-06-02 20:32:23 UTC], ["local_da_prova_id", 6], ["distribuicao",   "[{\"cargo_id\":\"4\",\"quantidade_de_candidatos\":\"10\"},{\"cargo_id}]"]] 
(0.2ms)  
ROLLBACK
Completed 500 Internal Server Error in 108ms (ActiveRecord: 6.3ms)

 ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR:  duplicate    key value violates unique constraint "index_distribuicao_por_cargos_on_local_da_prova_id"
DETAIL:  Key (local_da_prova_id)=(6) already exists.
: INSERT INTO "distribuicao_por_cargos" ("created_at", "updated_at", "local_da_prova_id", "distribuicao") VALUES ($1, $2, $3, $4) RETURNING "id"):

Upvotes: 0

Views: 1474

Answers (1)

Gerry
Gerry

Reputation: 10507

This happens because you are not validating in your model, so when it tries to create the record it fails, with an exception.

To avoid that, you could add a validation in your model, which will check if the column is unique; if validation succeeds then the record will be created, otherwise it will return false and create an error message (instead of raising an exception).

You can do this adding uniqueness: true in your model validations, like this:

class DistribuicaoPorCargo < ApplicationRecord
  # scopes, callbacks, ...

  validates :local_da_prova_id, uniqueness: true
  # more validations
end

This way, your controller will respond with:

render json: @distribuicao.errors.full_messages, status: :unprocessable_entity

and won't raise an exception (which prevent Completed 500 Internal Server Error from showing up).

Upvotes: 1

Related Questions