[英]Importing specific rows and columns from a CSV with rails
require 'csv'
CSV.foreach(filename, :headers => true) do |row|
if column3 = true || column 4 = true
Model.create!(row.to_hash)
else
skip
end
end
首先,有沒有辦法只在row.to_hash
抓取某些列?
第二,我是否使用if
語句獲取特定行的最佳方法? 我可以將整個CSV加載到各種各樣的臨時表中,然后抓住我需要的東西嗎?
row.to_hash
將根據標頭生成屬性哈希。 要選擇一組特定的屬性,您應該使用切片。
>> row.to_hash # { :attr1 => 'val1', :attr2 => 'val2', :attr3 => 'val3' }
>> row.to_hash.slice(:attr1, :attr2) # { :attr1 => 'val1', :attr2 => 'val2' }
關於你的第二個問題:是的,你仍然需要加載整個csv並檢查每一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.