I want to create multiple records at once but if there are any record which was not created because of any validation error then it should handle that error in some way.
PARAMETERS
Parameters: {"group"=>[{"sort_by"=>"id", "template_ids"=>[182], "name"=>"Csdfwses", "count"=>1}, {"sort_by"=>"id", "template_ids"=>[181], "name"=>"rthydrt", "count"=>1}]}
So my controller's create
method is like this:
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
i want to handle the case if there is any error occurred while creating any record such that after creating it should display the error message.
With the above approach there is no way to use error
method here. How to show the error messages?
I tried using 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
But i'm looking for the cleaner approach if there is any?
You want to pass an array of hashes to model.create
to create multiple records at once.
def create
@groups = Group.create group_params
if @groups.all? { |group| group.persisted? }
render json: { success: true, message: "#{@groups.length} groups created" }
else
render_422 @groups, 'Could not save groups.'
end
end
If you want to display any validation errors, then you will want to look in model.errors
or for a nice array of errors you can look at model.errors.full_messages
.
def create
@groups = Group.create group_params
if @groups.all? { |group| group.persisted? }
render json: { success: true, message: "#{@groups.length} groups created" }
else
errors = @groups.select(&:invalid?).map{ |g| g.errors.full_messages }.join("<br/>")
render_422 @groups, "Could not save groups. Here are the errors: #{errors}"
end
end
You will want to format the errors better, but this is a simple example.