GavinBelson
GavinBelson

Reputation: 2794

Rails returning validation error message from model method

I am calling an import method in my controller that imports a file. If in the import it tries to save the object and fails a model validation, how would I return the validation error messages to the project_data_path (or some other way of getting back to the index view)?

I tried an if statement in the controller, but it just gives me a validation failed error

Controller

def import
  if Datum.import(params[:file],params[:project_id])
    redirect_to project_data_path, notice: "data imported."
  else
    redirect_to project_data_path #if import fails, need to send errors
  end
end

Model

def self.import(file, proj_id)
    ##.. working logic that imports file into datum..##

    ## below works fine if there are no validation errors
    datum.save! ##model validation error happens here

  end
end

Upvotes: 0

Views: 537

Answers (1)

Vasili
Vasili

Reputation: 905

save! throws an exception, while save just returns true or false. Just remove the exclamation mark.

Upvotes: 1

Related Questions