在自定义控制器操作中呈现错误消息

时间:2011-12-30 14:16:44

标签: ruby-on-rails ruby-on-rails-3 activerecord

我已将以下内容添加到控制器的创建操作中:

 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
在我的BatchUser模型中,

'mass_insert_v2'就像这样开始:

 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 个答案:

答案 0 :(得分: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)放入flash中或使用类似dynamic_form plugin的内容。

相关问题