0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that was the issue, after removing the !, I was able to add return datum.errors to read the errors
@HoosierCoder congratulations!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.