传递给控制器​​的模型Ruby Rails中的验证失败

时间:2016-12-20 19:29:18

标签: ruby-on-rails ruby validation activerecord

所以我正在为TiProject模型进行CSV导入,我在模型中设置了验证,以便查看TiProject.protype是否存在于Projecttype.protype列表中。它工作,如果它无法验证它崩溃,很好。现在,我也有一个救援到位,所以我可以让人们知道,嘿,你的东西没有上传。我想具体说出它失败的验证。我只是不知道如何在下面的代码中访问errors.add(:base,“xyz”)并将其显示在通知中。

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....

1 个答案:

答案 0 :(得分: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