【问题标题】:Failed validation in model Ruby Rails passing to controller传递给控制器​​的模型 Rub​​y Rails 验证失败
【发布时间】:2016-12-20 19:29:17
【问题描述】:

所以我正在为 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....

【问题讨论】:

    标签: ruby-on-rails ruby validation activerecord


    【解决方案1】:
    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
    

    【讨论】:

    • 谢谢佩德罗,我真的很感激。与模型中的多种验证方法一起工作得很好。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    相关资源
    最近更新 更多