You could do it with a single sql query.
https://github.com/axsh/openvnet/blob/5c3b8c53c40f054fb50a5644e525e439f83a5822/vnet/lib/vnet/models/datapath_network.rb#L11-L32