csvruby-on-rails-5roo

How to omit empty rows using last_row in Roo Rails


I have a spreadsheet of members designed as below: enter image description here

My aim is to upload some columns and exclude others. In this case, I wish to upload only the name, age and email and exclude the others. I have been able to achieve this using the slice method as shown below:

def load_imported_members
    spreadsheet = open_spreadsheet
    spreadsheet.default_sheet = 'Worksheet'
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      member = Member.find_by_id(row["id"]) || Member.new
      member.attributes = row.to_hash.slice("id", "name", "age", "email")
      member
    end
  end

The problem is that last_row considers all the rows upto the last one (13), and since there are validations on the form, there are errors due to missing data as a result of the empty rows (which shouldn’t be considered). Is there a way I can upload only specific columns as I have done, yet limit to only the rows that have data?


Solution

  • You might want to chain the map call off of a reject filter like this example

    You may just need to change the map line to this (assuming the missing rows all look like those above): (2..spreadsheet.last_row).reject{|i| spreadsheet.row(i)[0] }.map do |i|

    This is assuming the blank rows return as nil and that blank rows will always have all four desired fields blank as shown in the image. The reject call tests to see if spreadsheet.row(i)[0], the id column, is nil, if so the item is rejected from the list output given to map