How to create multiple records and handle validations with create method in rails?
<p>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.</p>

<p>As i need to create multiple groups at once.</p>

<p><strong>PARAMETERS</strong></p>

<pre><code>  Parameters: {"group"=&gt;[{"sort_by"=&gt;"id", "template_ids"=&gt;[182], "name"=&gt;"Csdfwses", "count"=&gt;1}, {"sort_by"=&gt;"id", "template_ids"=&gt;[181], "name"=&gt;"rthydrt", "count"=&gt;1}]}
</code></pre>

<p>So my controller's <code>create</code> method is like this:</p>

<pre><code>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
</code></pre>

<p>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.</p>

<p>With the above approach there is no way to use <code>error</code> method here. How to show the error messages?</p>

<p>I tried using <a href="http://api.rubyonrails.org/classes/ActiveRecord/RecordInvalid.html" rel="nofollow">begin-rescue</a>:</p>

<pre><code> 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 =&gt; invalid
    render json: { success: false, message: "#{invalid.record.errors.messages}" }, status: 500
  end
 end
</code></pre>

<p>But i'm looking for the cleaner approach if there is any?</p>