Well, there are a few approaches you could take to do this.
1. Controller actions defining a logical "function"
Make the process of inserting all the records, externally, as a
controller action. Allowing you to do them sequentially.
2. Use ActiveRecord hooks
Take a look at the hooks like #after_save, #before_save, etc.
Active Record gives you API to build, save, and retrieve this stuff at
a high-level. In particular it handles recursive save and FK
assignment for you:
puts "dumping shelf #{shelf.name}, which has #{shelf.cards.count} cards"
for card in shelf.cards
puts "dumping card #{card.name}, which has #{card.ports.count} ports"
for port in card.ports
puts "shelf #{shelf.id} - card #{card.id} - port #{port.id}"
end
end