Actually, in an ionic bond, the metal is said to lose an electron, not gain one (this is the case for alkali metals) ; the nonmetal that bonds with such a metal can be said to gain an electron.
Let's take an easy example, sodium chloride -
SInce sodium is an alkali metal - it's in group I of the periodic table, it has 1 electron in its outermost shell. SInce the goal of (almost) every atom is to reach a complete outer shell - that is ,to have 8 electrons in its outermost shell- it's easier for
Since chlorine is a halogen (a group 17 nonmetal), it has 7 electrons in its outermost shell, so it would only need one electron to do that.
So, when an ionic bond is formed between
This is true for alkali earth metals as well; metals found in group II of the periodic table will donate 2 electrons when forming an ionic bond with a nonmetal.