MΓ³dulo 07 Β· ActiveRecord β LecciΓ³n 5 de 5 Β· ~12 min
Seeds & the N+1 Trap
db/seeds.rb β idempotent, on purpose
db/seeds.rb is where you describe data every environment needs to boot with something real in it β a few walkers, a dog, a demo booking β run with bin/rails db:seed. The trap: if you write plain Walker.create!(...), running db:seed twice creates two identical walkers. The fix is find_or_create_by!, which looks for a matching row first and only creates one if it's missing:
Walker.find_or_create_by!(name: "Priya") do |walker| walker.city = "Austin" walker.price_per_30_min_cents = 2400 end
The block only runs on CREATE, not on an existing match β so re-running db:seed after the walker already exists just finds it and moves on, no duplicate, no error. This exact pattern is how the real backend's apps/pawwalk-api/db/seeds.rb works too β every find_or_create_by! there, none of them plain create!.