简体   繁体   中英

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 ?

Second, is my use of the if statement the best way to grab particular rows? Could I just load the entire CSV to some sort of staging table of sorts, and then grab what I need?

row.to_hash will produce a hash of attributes based on the headers. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM