【发布时间】:2016-05-19 21:20:36
【问题描述】:
我将参数中的一组属性发送到我的控制器,如果在创建记录时出现任何错误,我需要处理验证错误。
因为我需要一次创建多个组。
参数
Parameters: {"group"=>[{"sort_by"=>"id", "template_ids"=>[182], "name"=>"Csdfwses", "count"=>1}, {"sort_by"=>"id", "template_ids"=>[181], "name"=>"rthydrt", "count"=>1}]}
所以我的控制器的create方法是这样的:
def create
@groups = Group.create group_params
if @groups
render json: { success: true, message: "#{@groups.length} groups created" }
else
render_422 @groups, 'Could not save groups.'
end
end
如果在创建任何记录时出现任何错误,我想处理这种情况,以便在创建后显示错误消息。
使用上述方法,这里无法使用error 方法。如何显示错误信息?
我尝试使用begin-rescue:
def create
begin
@groups = Group.create! group_params
if @groups
render json: { success: true, message: "#{@groups.length} groups created" }
else
render_422 @groups, 'Could not save groups.'
end
rescue ActiveRecord::RecordInvalid => invalid
render json: { success: false, message: "#{invalid.record.errors.messages}" }, status: 500
end
end
但如果有的话,我正在寻找更清洁的方法?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4