active record multiple table insert

If I have a shelf table, card table and port table how do I go about
inserting data into each table relating one to another?

Insert name of the shelf and # of cards the shelf has, and the name of
each card and other data, and how many ports on each card?

Shelf has many cards.
Card has many ports.

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:

shelf = Shelf.new(:name => 's')

card1 = shelf.cards.build(:name => 'c1')
card2 = shelf.cards.build(:name => 'c2')

1.times {card1.ports.build}
2.times {card2.ports.build}

shelf.save

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

I tried to do shelf.cards.count and I get an error saying it cannot
find shelf.id in the cards table.