In an exercise of Eisenbud-Harris The Geometry of Schemes, they ask to prove the following:
Let $S$ be any scheme. Let $\mathbb{A}_{\mathbb{Z}}^n = \mathrm{Spec}\mathbb{Z}[x_1, \dots , x_n]$ be the affine space over $\mathrm{Spec} \mathbb{Z}$. show that the affine space $\mathbb{A}_S^n$ over $S$ may be described as a product: $\mathbb{A}_S^n = \mathbb{A}_{\mathbb{Z}}^n \times_{\mathrm{Spec} \mathbb{Z}} S$.
The problem is that the definition for the fibered product of schemes $X \times_S Y$ they give in the book works when $S$ is not affine and we have a covering of $S$ by affine spectra $\mathrm{Spec} R_i$. Then we cover $Y$ and $X$ with the preimages of $\mathrm{Spec} R_i$ under the maps $X \to S$ and $Y \to S$ and glue together the resulting fibered product of affine schemes.
However, in this case, both $\mathbb{A}_{\mathbb{Z}}^n$ and $\mathrm{Spec} \mathbb{Z}$ are affine, and thus I don't know how apply their construction to this case. I thought of the following.
If $S = \mathrm{Spec} R$, then $$\mathrm{A}_{\mathbb{Z}}^n \times_{\mathrm{Spec} \mathbb{Z}} \mathrm{Spec} R = \mathrm{Spec}( \mathbb{Z}[x_1, \dots , x_n] \otimes_{\mathbb{Z}} R) = \mathrm{Spec}(R[x_1, \dots , x_n]) = \mathbb{A}_R^n \, .$$
Then, if we cover $S$ by affine schemes $U_i = \mathrm{Spec}R_i$, we can consider the affine schemes $$\mathbb{A}_{\mathbb{Z}}^n \times_{\mathrm{Spec} R} \mathrm{Spec} R_i = \mathbb{A}_{R_i}^n$$ and then glue them by the maps induced by the identity maps on $U_i \cap U_j$.
If this indeed gives us a fibered product, then the construction agrees with the one they do when defining $\mathbb{A}_S^n$, but I'm not entirely sure.
I believe you would like to see $\mathbf{A}_S^n$ as spectrum of some "ringed" thing even if $S$ is not affine.
This is not only reasonable, but actually true! However, the tool you need is not the algebraic spectrum of a ring but the relative Spec construction. If you are not familiar with it, see for example Stacks project.
Let $S$ be any scheme and let $\mathscr{O}_S$ be the structure sheaf. For every $n>0$ one can construct the quasi-coherent sheaf of $\mathscr{O}_S$-algebras $$\mathscr{O}_S[t_1,\ldots,t_n]:= \bigoplus_{i=1}^n \mathscr{O}_S$$.
Then we defined the affine space of dimension $n$ over $S$ as $$\mathbf{A}_S^n :=\mathbf{Spec} (\mathscr{O}_S[T_1 ,\ldots ,T_n])$$
This definition leads to the one you were given by considering the properties of the base change for the relative spectrum, that is to say: for every morphism of schemes $f:U\to S$ and for every sheaf of $\mathscr{O}_S$-algebras $\mathscr{A}$, one has
$$ U\times _S \mathbf{Spec}(\mathscr{A}) \simeq \mathbf{Spec}(f^* \mathscr{A})$$
Now, in our case it is immediate to see that $f^* \mathscr{O}_S[T_1,\ldots, T_n] \simeq \mathscr{O}_U [T_1,\ldots, T_]$ so
$$U\times_S \mathbf{A}^n_S \simeq \mathbf{A}^n_U$$
So taking $S = \mathrm{Spec}\,\mathbb {Z}$ and $f$ as the structure morphism of $U$ we obtain your definition.