[英]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.