Importing specific rows and columns from a CSV with rails

csv, import, ruby-on-rails

Solution

`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.

Problem

``` 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?

Original source