Ruby on rails 传递给控制器的Ruby Rails模型验证失败
因此,我正在为TiProject模型进行CSV导入,并在模型中设置了验证,以便查看Projecttype.protype列表中是否存在TiProject.protype。它可以工作,如果它不能验证它就会崩溃,太好了。现在,我也有一个救援行动,这样我可以让人们知道,嘿,你的东西没有上传。我想特别指出它失败的原因。我只是不知道如何访问这些错误。在下面的代码中添加(:base,“xyz”),并让它显示在通知中 ti_project.rbRuby on rails 传递给控制器的Ruby Rails模型验证失败,ruby-on-rails,ruby,validation,activerecord,Ruby On Rails,Ruby,Validation,Activerecord,因此,我正在为TiProject模型进行CSV导入,并在模型中设置了验证,以便查看Projecttype.protype列表中是否存在TiProject.protype。它可以工作,如果它不能验证它就会崩溃,太好了。现在,我也有一个救援行动,这样我可以让人们知道,嘿,你的东西没有上传。我想特别指出它失败的原因。我只是不知道如何访问这些错误。在下面的代码中添加(:base,“xyz”),并让它显示在通知中 ti_project.rb class TiProject < ActiveRecor
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.....
class项目
ti_项目_控制器.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....
class TiProjectsController:rescue上载
def索引
@tiprojects=TiProject.all
结束
def导入
导入(参数[:文件])
TiProject.checkforpidtc
重定向到ti_项目路径,注意:“项目上传成功”
结束
def上传
重定向到ti项目路径,注意:“项目上传错误”
结束
其他东西。。。。
谢谢佩德罗,我真的很感激。可在模型中使用多种验证方法。=)
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