[英]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
First, is there a way to only grab certain columns during the row.to_hash
? 首先,有没有办法只在row.to_hash
抓取某些列?
Second, is my use of the if
statement the best way to grab particular rows? 第二,我是否使用if
语句获取特定行的最佳方法? Could I just load the entire CSV to some sort of staging table of sorts, and then grab what I need? 我可以将整个CSV加载到各种各样的临时表中,然后抓住我需要的东西吗?
row.to_hash
will produce a hash of attributes based on the headers. row.to_hash
将根据标头生成属性哈希。 To select a particular set of attributes, you should use slice. 要选择一组特定的属性,您应该使用切片。
>> row.to_hash # { :attr1 => 'val1', :attr2 => 'val2', :attr3 => 'val3' }
>> row.to_hash.slice(:attr1, :attr2) # { :attr1 => 'val1', :attr2 => 'val2' }
About your second question: YES, you still need to load the entire csv and just check against each row. 关于你的第二个问题:是的,你仍然需要加载整个csv并检查每一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.