私はtsv(タブで区切られたデータ)ファイルをデータベースにインポートしようとしていますが、フォーマットされていません。 price
とcount
の列はスペースで区切られ(ヘッダー行を除く)、値は両方ともprice
キーに置かれ、すべてのデータが間違ったキー値のペアに移動します。RailsはCSVファイルのデータを正規化します
TSVファイル:/models/purchase.rb
で
purchaser name item description price count merchant address merchant name
Alice Bob $10 off $20 of food 10.0 2 987 Fake St Bob's Pizza
Example Name $30 of awesome for $10 10.0 5 456 Unreal Rd Tom's Awesome Shop
Name Three $20 Sneakers for $5 5.0 1 123 Fake St Sneaker Store Emporium
John Williams $20 Sneakers for $5 5.0 4 123 Fake St Sneaker Store Emporium
:
class Purchase < ActiveRecord::Base
# validates :item_price, :numericality => { :greater_than_or_equal_to => 0 }
def self.import(file)
CSV.foreach(file.path, :headers => true,
:header_converters => lambda { |h| h.downcase.gsub(' ', '_')},
:col_sep => "\t"
) do |row|
# debugger
purchase_hash = row.to_hash
Purchase.create!(purchase_hash)
end
end
end
私がモデルにデバッガでファイルとコメントをインポートしてrow
を入力した場合、それが返されます。
#<CSV::Row "purchaser_name":"Alice Bob" "item_description":"$10 off $20 of food" "price":"10.0 2" "count":" 987 Fake St" "merchant_address":" Bob's Pizza" "merchant_name":nil>
row.inspect
のリターン:あなたが見ることができるように、彼らはファイルにタブ区切りなかったため
"#<CSV::Row \"purchaser_name\":\"Alice Bob\" \"item_description\":\"$10 off $20 of food\" \"price\":\"10.0 2\" \"count\":\" 987 Fake St\" \"merchant_address\":\" Bob's Pizza\" \"merchant_name\":nil>"
price
(10.0)とcount
(2)は同じ値に踏み付けられています。
db/schema.rb
:
ActiveRecord::Schema.define(version: 20160601205154) do
create_table "purchases", force: :cascade do |t|
t.string "purchaser_name"
t.string "item_description"
t.string "price"
t.string "count"
t.string "merchant_address"
t.string "merchant_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
私はもともと整数として小数点データ型としてprice
とcount
があったが、解決策を見つけることを試みるために文字列にそれらをスイッチバック。
本当にありがとうございました – alisontague