从模型方法返回验证错误消息的Rails

问题描述:

我在我的控制器中调用导入方法来导入文件。如果在导入时尝试保存对象并且未通过模型验证,那么我将如何将验证错误消息返回到project_data_path(或返回索引视图的其他方式)?从模型方法返回验证错误消息的Rails

我试图在控制器中的if语句,但它只是给了我一个验证失败的错误

控制器

def import 
    if Datum.import(params[:file],params[:project_id]) 
    redirect_to project_data_path, notice: "data imported." 
    else 
    redirect_to project_data_path #if import fails, need to send errors 
    end 
end 

型号

def self.import(file, proj_id) 
    ##.. working logic that imports file into datum..## 

    ## below works fine if there are no validation errors 
    datum.save! ##model validation error happens here 

    end 
end 

save!抛出一个异常,而save只返回truefalse。只需删除感叹号。

+0

是的,这是问题,在删除!后,我能够添加'返回datum.errors'来读取错误 – HoosierCoder

+0

@HoosierCoder祝贺! –