[Ruby on Rails] How to use seed-fu for easy seed data addition and management
I’d like to introduce the convenient seed-fu gem that makes adding and managing seed data easy in Ruby on Rails.
The usage is to create files like users.rb under db/fixtures, and write them simply like this:
db/fixtures/users.rb
User.seed do |s|
s.id = 1
s.login = "jon"
s.email = "[email protected]"
s.name = "Jon"
end
User.seed do |s|
s.id = 2
s.login = "emily"
s.email = "[email protected]"
s.name = "Emily"
end
To import from all seed files, simply run:
rake db:seed_fu
To load by file or model, run rake tasks like this:
rake db:seed_fu FIXTURE_PATH=path/to/fixtures
rake db:seed_fu FILTER=users,articles
Since you can write Ruby code, you can also write things like importing from CSV to DB:
db/fixtures/users.rb
require 'csv'
csv = CSV.read('db/fixtures/users_master.csv')
csv.each_with_index do |user, i|
# skip a label row
next if i === 0
name = user[0]
age = user[1].to_i
User.seed do |s|
s.id = i
s.name = name
s.age = age
end
end
It’s subtly convenient.
That’s all from the Gemba.