Save multiple object in Controller from a single call

I’m trying to create multiple objects through Controller with a single call. However I’m getting ActiveModel::ForbiddenAttributesError:

Params:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"JOBnvYmshIefa2LeKkaMeaN+dHYq+VZlUPmmi4++I3Y=", "student_ids"=>"1,2", "message"=>{"content"=>"{{first_name}}"}, "commit"=>"Create Message"}

My actions:

  def create
    # Build arrays of data
    arr = Array.new
    params[:student_ids].split(",").each do |id|
      h = params[:message].merge("student_id" => id, "center_id" => current_center.id)
      arr << h
    end

    new_params = ActionController::Parameters.new(data: arr)
    new_params.permit(data: [:content, :student_id, :center_id])

    if Message.create(new_params)
      redirect_to new_message_path, notice: 'Message was successfully created.'
    else
      render action: 'new'
    end
  end

Any idea on how to solve it?

@amree the code that your doing to build the new parameters is not straightforward, I think you should really consider attempting to change whatever is submitting to this create action to submit the parameters in the format you expect. Is that possible?

Otherwise, it would be helpful if you could provide what new_params is here, for debugging purposes. I’d guess that it does not match what you are permitting, and therefore you’re getting the ActiveModel::ForbiddenAttributesError

I’m still not sure what you meant in the first paragraph, however, new_param is based on value from arr which was built using these codes:

arr = Array.new
params[:student_ids].split(",").each do |id|
  h = params[:message].merge("student_id" => id, "center_id" => current_center.id)

  arr << h
end