Task to add Indian states to spree database.
1) Add a text file with extension .rake to the folder lib/tasks/
example:-lib/tasks/mytask.rake
2) add file content as follows
task :add_indian_states=>:environment do
CSV.foreach(“lib/tasks/states.csv”) do | row |
state, abbr = row
Spree::State.create(:name => state,:abbr=> abbr,:country_id=>3)
end
end
3) add file “states.csv” to lib/tasks/ with file content as follows
“Andhra Pradesh”,” AP”
“Arunachal Pradesh”,” AR”
“Assam”,” AS”
“Bihar”,” BR”
“Chhattisgarh”,” CT”
“Goa”,” GA”
“Gujarat”,” GJ”
“Haryana”,” HR”
“Himachal Pradesh”,” HP”
“Jammu & Kashmir”,” JK”
“Jharkhand”,” JH”
“Karnataka”,” KA”
“Kerala”,” KL”
“Madhya Pradesh”,” MP”
“Maharashtra”,” MH”
“Manipur”,” MN”
“Meghalaya”,” ML”
“Mizoram”,” MZ”
“Nagaland”,” NL”
“Odisha”,” OR”
“Punjab”,” PB”
“Rajasthan”,” RJ”
“Sikkim”,” SK”
“Tamil Nadu”,” TN”
“Tripura”,” TR”
“Uttarakhand”,” UT”
“Uttar Pradesh”,” UP”
“West Bengal”,” WB”
“Andaman & Nicobar”,” AN”
“Chandigarh”,” CH”
“Dadra and Nagar Haveli”,” DN”
“Daman & Diu”,” DD”
“Delhi”,” DL”
“Lakshadweep”,” LD”
“Puducherry”,” PY”
4) want to add the following to config/application.rb to work with CSV library
require ‘csv’
5) here “country_id=3” denotes INDIA as foreign key.
you can avoid step 6 in later versions of spree and rails if this raise error
6) you want to make new file state_decorator.rb with the following content to the folder app/models to avoid rails Mass assignment error.
Spree::State.class_eval do
attr_accessible :country_id
end
7) rake add_indian_states will run the task. ( rails will detect the task name from the file which is the folder lib/tasks)
Rake Reference
railscasts 362
http://jasonseifer.com/2010/04/06/rake-tutorial
http://blog.jayfields.com/2006/11/ruby-testing-rake-tasks.html
http://lukaszwrobel.pl/blog/rake-tutorial
http://railsguides.net/2012/03/14/how-to-generate-rake-task/
csv reference
http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html
www.klairvoyant.in
10.619223
76.039038