Performance: Seed data
Seed data affects initial page load speed indirectly by impacting database size and query performance during development and testing.
users = (1..1000).map { |i| {name: "User #{i}", email: "user#{i}@example.com", created_at: Time.now, updated_at: Time.now} } User.insert_all(users)
1000.times do |i| User.create(name: "User #{i}", email: "user#{i}@example.com") end
| Pattern | Database Operations | Query Count | Seed Time | Verdict |
|---|---|---|---|---|
| Single record inserts in loop | 1000 inserts | 1000 queries | Several seconds | [X] Bad |
| Bulk insert with insert_all | 1 insert | 1 query | Milliseconds | [OK] Good |
bin/rails db:seed.rails generate seed is not a valid command, bin/rails db:create creates the database, and rails server starts the server.db/seeds.rb:
3.times do |i|
User.create(name: "User #{i + 1}")
end
What will be the names of the users created after running bin/rails db:seed?i values 0, 1, 2.i + 1, so names are "User 1", "User 2", "User 3".User.create(name: "Alice") User.create(name: "Bob") User.create(name: )
name: with no value, which is a syntax error.find_or_create_by which checks existence before creating. Category.delete_all
['Books', 'Movies', 'Music'].each do |name|
Category.create(name: name)
end deletes all categories first, which is destructive. Category.create(['Books', 'Movies', 'Music']) tries to create with an array directly, which is invalid syntax.Pass the test and this pattern moves unknown