At the article Rails 4 : Load Seed from TSV, I wrote about how to inject tsv seed data into your db. This time, I wrote about how to inject not only tsv, also csv seed data into your db.
Continue reading RAILS 4 : Load Seed from TSV and CSVTag Archives: seed
Rails How to execute task in seed
Here’s how I executed task in seeds.rb
, in Rails.
Environment
- Ruby 2.2.2p95
- Rails 4.1.8
- Rake 10.4.2
First, create a task with rails g task sample shot
. The following code will be generated.
1 2 3 4 5 6 |
namespace :sample do desc "shot sample" task shot: :environment do # something to do end end |
Now, we can execute the task with bundle exec rake sample:shot
. The goal is to execute the task when bundle exec rake db:seed
is executed. Maybe, it is the same way to execute task in rails code.
Solution
Add the code into seeds.rb
, like below.
1 2 |
ENV['SOMETHING'] = 'value' Rake::Task['sample:shot'].invoke |
Environment (test, development, production) is passed, which is valid in rake db:seed
. On the above, set 'value'
to SOMETHING
. It is like FEATURES in rake db:fixture:load FIXTURES=xxxx
.