ruby-on-railscsvroo-gem

Upload excel data using a combination of two columns?


I have an excel sheet which has the format shown below: enter image description here

Members can have multiple entries in the corresponding members table. When uploading data from the excel template, I would like to find_by pin as well as end_date so that I update the specific record during upload.

I am using gem roo to import excel data, and here is my load_imported_members method:

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_pin(row["pin"]) || Member.new
      member.attributes = row.to_hash.slice("id", "name", "pin", "end_date", "email")
      member
    end
  end

I reckon that if I use both pin and end_date in the find_by method, I will update the specific record, since there could be two entries in the table, but one must have an end_date. How can I achieve this? Thanks


Solution

  • If you want to find just one record at a time you can use a find_by() with a hash to search with multiple columns like this:

    Member.find_by(pin:row["pin"],end_date: row["end_date"])

    find_by is explained more here

    If you want to retrieve multiple records matching your search you need the where() function on the Member class instead of find_by()

    where is explained more here