jimps
jimps

Reputation: 65

Rails importing via CSV and setting fields at the same time

I have the ability to import people details via CSV as entries.

If the spreadsheet contains no id on that row, it creates the entry, otherwise it updates the entry according to the id number.

Ultimately, what I want to do is to have the 'CreatedAt' field update when importing the entry if there is no id, otherwise, leave it alone (each entry only needs 'CreatedAt' to be set once).

If there already is a 'CreatedAt' set and we are just updating, it needs to do nothing.

This is the code I have so far:

controller file:

def import
 Votsphonebook.import(params[:file])
 redirect_to root_url, notice: "Entries updated!"
end

model file:

def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|

        votsphonebook_hash = row.to_hash 
        votsphonebook = Votsphonebook.where(id: votsphonebook_hash["id"])

        if votsphonebook.count == 1
            votsphonebook.first.update_attributes(votsphonebook_hash)
        else

            Votsphonebook.create!(votsphonebook_hash)
        end
    end
end

I just need an entry point in my code where I can take the current row it is looking at and run the if statement.

Thank you

Upvotes: 0

Views: 75

Answers (1)

rebagliatte
rebagliatte

Reputation: 2146

The updated_at and created_at columns are automatically populated by Active Record. There are no additional steps required to achieve what you want.

If you want to capture the current time on a custom column you could do this:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    votsphonebook_hash = row.to_hash
    votsphonebook = Votsphonebook.find(votsphonebook_hash["id"])

    if votsphonebook
      votsphonebook.update_attributes(votsphonebook_hash.merge(your_custom_column: Time.now))
    else
      Votsphonebook.create!(votsphonebook_hash)
    end
  end
end

Please note I refactored your finder a little bit for clarity.

Upvotes: 1

Related Questions