2011-12-30 85 views
2

我已经添加了以下到我的控制器的创建操作渲染错误消息:在自定义控制器动作

def create 
    BatchUser.mass_insert_v2(params[:batch_user][:batch_name], params[:batch_user] [:batch_description], params[:batch_user][:quantity]) 
    redirect_to batch_users_path 
end 

“mass_insert_v2”,在我BatchUser模式,开始是这样的:

def self.mass_insert_v2(batch_name, batch_description, quantity) 
    @batch_create = BatchUser.create! :batch_name => batch_name, :batch_description => batch_description 
    ... 
end 

而且然后继续创建具有随机用户名和密码的X用户帐户。我选择了这条路线是因为我发现原始的sql插入比自己使用activerecord更快。

我遇到的问题是我努力呈现我的错误消息。例如,batch_name必须存在且唯一。

我得到一个错误的屏幕:

ActiveRecord::RecordInvalid in BatchUsersController#create 

但没有错误显示。

以前,我有这个检查在我的控制器:

respond_to do |format| 
    if @batch_user.save 
    .... 
    else 
    .... 

但是,这似乎并没有工作了。我能做些什么来显示页面上的错误?

回答

1

创建! (用bang创建!)会在对象失败验证时抛出异常。除非你计划捕获这个异常,并且处理你可能会更好,只需使用create,然后检查对象是否已成功创建(有一个id)和/或是否有错误。

处理查找和渲染错误信息有几种不确定的方式,以便您可以进行实验。然而,知道与重要的注意事项以及按照上面会帮助你的轨道上,我认为:

@batch_user = BatchUser.create(attr_hash) #will give you an object to work with instead of throwing an exception. 

如果你有一个现有对象:

@batch_user.valid? #will trigger the validations only and set the object's errors attribute with any relevant data and return a boolean value. 

@batch_user.errors #gives you access to the error data (in 3.1 ActiveModel::Errors object) 

至于实际渲染错误,好像我说有几种选择。我更喜欢将这些错误消息(obj.errors.full_messages)放在闪存中或使用类似dynamic_form plugin的东西。

+0

很酷,当我回来生病检查出来。 s – simonmorley 2011-12-30 15:55:40

+0

谢谢,一直在阅读。将这些验证检查放在控制器或模型中最好吗? S – simonmorley 2011-12-31 13:58:43

+0

通过一些实验回答了我自己的问题。将创建从模型移动到控制器,然后在if else循环中运行额外部分。干杯 – simonmorley 2011-12-31 14:10:01