0
Posted September 19, 2012 by Spyros in Ruby on Rails
 
 

Seeding Your Database With Style

seeds-300x225
seeds-300x225

One of the biggest problems that i always had when i was creating new Rails projects is the need for a versatile way to seed my database. There are various gems that make this procedure rather easy, but they tend to create repeating code with Factories and the likes. I would mostly like a way to create my entries in a concise and easy to edit manner. Therefore, i created a simple custom way to do that. I haven’t made it a gem yet, but i most probably will if people like this approach.

The idea is that the seeds.db file is just the control panel of my other seed files. So, let’s say that i want to populate my database with some users. The first thing i would do is edit my seeds.db file like so :

(seeds.rb)

load "#{Rails.root}/db/seed_data/seed_users.rb"

This instructs seeds.db to load the file located in the “db/seed_data/seed_users.rb” path of your rails application. My seed_users.rb file contains :

(db/seed_data/seed_users.rb)

users = [

{
  :username => 'spyros',
  :email => 'email@gmail.com',
  :password => '...',
  :role => 'admin'
},

{
  :username => 'author',
  :email => 'new_author@gmail.com',
  :password => '...',
  :role => 'author'
},

{
  :username => 'another_user',
  :email => 'newmail@gmail.com',
  :password => '...'
}

]

users.each do |hash|
	user = User.new
	hash.each do |attribute, value|
	  user.update_attribute(attribute, value)
	end
end

Notice that ‘users’ is simply a ruby array that contains a series of hashes. These hashes represent entries for our database. You may be asking why i create a new User object and instead of directly saving it, i go about updating each attribute individually. I did that in order to bypass the “attr_accessible” method that you should have declared in your User model whatsoever. I found that this is probably the easiest way to bypass that security option, that you should always use. I will write a post to explain exactly what attr_accessible is and why you should always use it in your models, in case you are not aware of it. Moreover, notice that update_attribute does not validate your entries, while update_attributes does trigger validations.

If you find this seeding method useful, please let me know, so that i can create a simple gem to automate the process. It is useful for me, but i am not sure if others find this method useful. I would like to get some opinions :)


Spyros