settheline
settheline

Reputation: 3383

Updating rails database records with CSV import

I have the following controller method:

class InventoryItemsController < ApplicationController

    def import
        params.permit(:code, :vendor_id, :price)
        InventoryItem.import(params[:file])
        redirect_to admin_index_path, notice: "Inventory Imported."
    end
end

This then calls my model method:

class InventoryItem < ActiveRecord::Base

    def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
        InventoryItem.create! row.to_hash
    end
  end
end

What I want to now be able to do is use a similar CSV import method to update existing records (for price changes etc.), only adding new records if the :code attribute is unique. I could probably do this if it were a simple update for one record, but I'm not sure how to tackle this with a CSV upload. Help please? Thanks in advance!

Upvotes: 0

Views: 2309

Answers (1)

srt32
srt32

Reputation: 1270

This answer might help you out: create_or_update method in rails

Try using something like the below with find_or_initialize_by_code. Your code would look something like

def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
    my_object = InventoryItem.find_or_initialize_by_code(code)
    my_object.update_attributes(row.to_hash)
end

Upvotes: 1

Related Questions