Updating a Rails Seed File
In this guide we will update our application's seed file to keep it up to date with the changes made to the schema file.
Guide Tasks
  • Read Tutorial

Our application is coming along nicely, however our seeds file is looking a little out of date and as I'm building an app I like to keep my sample data up to date or it becomes stagnant and essentially worthless. Having RSpec tests are important, however it's also important to verify data in the browser and therefore it's very nice to have the capability of running a single command that will clean out old data and update it with new items.

I've had plenty of times in the past where I let my seeds file go out of date and I was getting errors in the browser that didn't have anything to do with the code, but were all related to outdated data.

Let's open up the seeds.rb file and see what needs to be changed. It looks like we simply need to have our admin user create a new AdminUser instead of a User, and then to remove the role from each create call. Those two statements should now look something like this:

# db/seeds.rb

AdminUser.create!(
  email: "admin@test.com",
  password: "asdfasdf",
  password_confirmation: "asdfasdf",
  first_name: "Jon",
  last_name: "Snow",
  username: "wallwatcher"
)

puts "Admin user created"

User.create!(
  email: "student@test.com",
  password: "asdfasdf",
  password_confirmation: "asdfasdf",
  first_name: "Jon",
  last_name: "Snow",
  username: "youngwallwatcher"
)

puts "Student user created"

This looks better, now let's run bundle exec rake db:set.

large

This will clear out all of the current sample data (DO NOT run this command if you're working on a production application, it will remove all of your data). Now if we open up the application we can login with our new AdminUser to ensure that it's working and it looks like our new data is working properly:

large

So now our sample data is up to date and we can keep moving along. You may have noticed when we logged in that our header isn't changing when a user is logged in, we'll take care of that in the next lesson.

Resources