Mike Rogers on a Snowmobile

Mike Rogers

Web Developer

Seeding with Seedbank

Posted on

In this tutorial I explain Seedbank, a gem that I use regularly that helps keep the seeds in your project organised.

Seeding class

To help keep the seed files as clean as possible, I've made a class that stops seeds being added twice and also outputs to the user what has been added to the database:

class Seeds
  def self.add model, attrs
    object = model.find_or_initialize_by(attrs)

    if object.new_record? && object.save
      puts "#{object}"
View on Gist Github

Here is how to implement the class in your seeds:

after :farms do
  puts 'Adding Users:'

  farm = Farm.find_by name: 'McCain'
  Seeds.add User, full_name: 'Mr McCain', is_manager: true, farm: farm
View on Gist Github

You can find all the code behind this tutorial in the GitHub Repo.

Share the ♥ by sharing this!

If you want to discuss this post, feel free to tweet me (@MikeRogers0) or drop me an email. Any code samples unless stated otherwise are licensed under the The MIT License (MIT). Spotted a mistake? Send me a pull request :)