2016-12-20 8 views
1

Also mache ich einen CSV-Import für TiProject-Modell und ich habe eine Validierung im Modell eingerichtet, so dass TiProject.protype in einer Liste von Projecttype vorhanden ist. protype. Es funktioniert und wenn es nicht bestätigt, stürzt es ab, großartig. Jetzt habe ich auch eine Rettung an Ort und Stelle, damit ich die Leute wissen lassen kann, hey, deine Sachen wurden nicht hochgeladen. Ich möchte ausdrücklich darauf hinweisen, welche Validierung fehlgeschlagen ist. Ich weiß einfach nicht, wie ich auf diese errors.add (: base, "xyz") im folgenden Code zugreifen kann, damit sie in der Benachrichtigung angezeigt wird.Fehlgeschlagene Validierung im Modell Ruby Rails übergibt an den Controller

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

Antwort

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 
+0

Dank Pedro, ich schätze das wirklich. Funktioniert fantastisch mit mehreren Validierungsmethoden im Modell. =) – bwatson30

+0

Schön! Bitte. –

Verwandte Themen