Ahmad hamza Ahmad hamza - 6 months ago 63
Ruby Question

How to create multiple records and handle validations with create method in rails?

I'm sending an array of attributes in parameter to my controller and i need to handle validation errors if there is any error in creating record.

As i need to create multiple groups at once.

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?

Dbz Dbz
Answer

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.map { |group| group.errors.full_messages.empty? nil : group.errors.full_messages }.compact.join("\n") # gross one-liner to show you where the errors live
    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.