1

So I'm doing a CSV import for TiProject model and I have a validation set up in the model such that it's looking to see if TiProject.protype exists in a list of Projecttype.protype. It works and if it fails to validate it crashes, great. Now, I also have a rescue in place so I can let people know, hey, your stuff didn't upload. I'd like to call out specifically what validation it failed. I just don't know how to access that errors.add(:base, "xyz") in the code below and get it to show up in the notice.

ti_project.rb

class TiProject < ActiveRecord::Base
validate :validate_protype

def validate_protype
  if Projecttype.find_by_protype(protype) == nil
  errors.add(:base, "Project type doesn't exist")
 end
end

def self.import(file)
 CSV.foreach(file.path, headers: true) do |row|
   TiProject.create! row.to_hash
 end
end 
other stuffs.....

ti_project_controller.rb

class TiProjectsController < ApplicationController
  rescue_from ActiveRecord::RecordInvalid, :with => :rescueuploads

def index
 @tiprojects =TiProject.all

end


def import
  TiProject.import(params[:file])
  TiProject.checkforpidtc
  redirect_to ti_projects_path, notice: "Projects uploaded successfully"
end


def rescueuploads
  redirect_to ti_projects_path, notice: "Project upload ERROR"
end
other stuffs....
0

1 Answer 1

3
def rescueuploads(exception)
  @error = exception
  @error.class
  @error.message #this is your message error raised from your model
  redirect_to ti_projects_path, notice: @error.message
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Pedro, I really appreciate that. Works fantastic with multiple validation methods in the model. =)

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.