HAML and nestings

I have this partial:
1 - bairros = bairros_select
2 - selected_id ||= nil
3 - if bairros.any?
4 - cid = nil
5 = select_tag :imovel, :bairro_id do
6 - for b in bairros
7 - sel = b.id == selected_id ? {:selected => true} : {}
8 - if cid != b.cidade_id
9 %optgroup= b.cidade.cidade
10 - cid = b.cidade_id
11 %option{sel, :value => b.id}= b.bairro

But seems I’m having problems to make the option element be rendered
as a child of optgroup element. Because optgroup is rendered
eventually multiple times.
Taking from the indentation above, the 11th line is child of “for in”
but actually it must be child of optgroup, despite optgroup (line 9)
is deeper in the indentation because the “if” statement from line 8.

How to solve this?

Best regards,
Leandro.