On Github itechdom / class-seed-data-rails
Setting up everything up by hand, which includes
Entering data in multiple lines instead of loops:
user_1 = User.create(name: "Richard", email: "richard@example.com", password: "asdf") user_2 = User.create(name: "Sam", email: "sam@example.com", password: "asdf") user_3 = User.create(name: "Sam", email: "sam@example.com", password: "asdf")
You set up relationships by hand:
order_2 = user_2.orders.create(amount: 10.00) order_2.items << item_2 puts "Created Order For: #{order_2.user.name}"
Let's go back to our example and look at how we can improve the way we write seed files:
Use loops instead of writing things in multiple lines:
10.times do |i| user = User.create(name: "user ##{i}", email: "email#{i}@example.com", password: "123") puts "Created User: #{user.name}" end
Setup Relationships using:
def generate_orders 100.times do |i| user = User.order("RANDOM()").limit(1).first user.orders.create(amount: i*2) do |order| rand(1..10).times do order.items << Item.order("RANDOM()").limit(1).first end end puts "Created Orders For: #{user.name}" end end
10.times do |i| user = User.create(name: "user ##{i}", email: "email#{i}@example.com", password: "123") puts "Created User: #{user.name}" end
In our previous example, let's convert our seed file to use Faker
def generate_users 10.times do user = User.create(name: Faker::Name.name, email: Faker::Internet.email, password: "asdf") puts "Created User: #{user.name}" end end
* Setup Relationships using Faker:
def generate_orders 100.times do user = User.order("RANDOM()").limit(1).first user.orders.create(amount: Faker::Commerce.price) do |order| rand(1..10).times do order.items << Item.order("RANDOM()").limit(1).first end end puts "Created Orders For: #{user.name}" end end