[英]Failed validation in model Ruby Rails passing to controller
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. 因此,我正在为TiProject模型进行CSV导入,并且在模型中进行了验证,以便查看是否在Projecttype.protype列表中存在TiProject.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. 我只是不知道如何在下面的代码中访问errors.add(:base,“ xyz”)并将其显示在通知中。
ti_project.rb 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 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....
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.