駅データ.jp から以下のようなファイルをダウンロードし、 db/seeds/ekidata
とか適当な場所に置く:
- station20121102free.csv
- line20121030free.csv
- company20121010.csv
マイグレーション:
# db/migrate/XXXXXXXXXXXXXX_create_ekidata_stations.rb
class CreateEkidataTables < ActiveRecord::Migration
def change
create_table :ekidata_companies do |t|
t.integer :company_cd
t.integer :rr_cd
t.string :company_name
t.string :company_name_k
t.string :company_name_h
t.string :company_name_r
t.integer :company_type
t.integer :e_status
t.integer :e_sort
t.timestamps
end
add_index :ekidata_companies, :company_cd
create_table :ekidata_lines do |t|
t.integer :line_cd
t.integer :company_cd
t.string :line_name
t.string :line_name_k
t.string :line_name_h
t.string :line_color_c
t.string :line_color_t
t.string :line_type
t.float :lon
t.float :lat
t.integer :zoom
t.integer :e_status
t.integer :e_sort
t.timestamps
end
add_index :ekidata_lines, :line_cd
add_index :ekidata_lines, :line_name
add_index :ekidata_lines, :company_cd
create_table :ekidata_stations do |t|
t.integer :station_cd
t.integer :station_g_cd
t.string :station_name
t.string :station_name_k
t.string :station_name_r
t.integer :line_cd
t.integer :pref_cd
t.string :post
t.string :add
t.float :lon
t.float :lat
t.string :open_ymd
t.string :close_ymd
t.integer :e_status
t.integer :e_sort
t.timestamps
end
add_index :ekidata_stations, :station_cd
add_index :ekidata_stations, :line_cd
add_index :ekidata_stations, :pref_cd
end
end
モデル:
# app/models/ekidata.rb
module Ekidata
def self.table_name_prefix
'ekidata_'
end
end
# app/models/ekidata/company.rb
class Ekidata::Company < ActiveRecord::Base
end
# app/models/ekidata/line.rb
class Ekidata::Line < ActiveRecord::Base
end
# app/models/ekidata/station.rb
class Ekidata::Station < ActiveRecord::Base
end
データインポート用の rake タスク:
# lib/tasks/ekidata.rake
def load_ekidata(clazz, key, file)
puts "Loading #{clazz}: #{file}"
csv = CSV.read(file, headers: true)
csv.each do |row|
clazz.where(key => row[0]).first_or_create do |i|
row.each do |key, data|
i[key] = data
end
end
end
end
desc 'load ekidata'
task load_ekidata: :environment do
load_ekidata(Ekidata::Station, :station_cd, Rails.root.join('db/seeds/ekidata/station20121102free.csv'))
load_ekidata(Ekidata::Line, :line_cd, Rails.root.join('db/seeds/ekidata/line20121030free.csv'))
load_ekidata(Ekidata::Company, :company_cd, Rails.root.join('db/seeds/ekidata/company20121010.csv'))
end
これで以下のようにして駅データを取り込める:
bundle exec rake load_ekidata