Tony Bagalini Tony Bagalini - 4 months ago 13
Ruby Question

importing a CSV and assign to current user ruby

I am trying to import a CSV file and assign the import to the current user. So, it will add the user_id to the each row of the csv import.

I am missing something because it still doesn't find the user and add it to the row...

Controller :

def import
Inventory.import(params[:file], current_user.id)
redirect_to root_url, notice: "Inventory imported."
end


Method:

class Inventory < ApplicationRecord
belongs_to :user

def self.import(file, user_id)
allowed_attributes = [ "user_id", "id","description","part_number","price","created_at","updated_at", "alternate_part_number", "condition_code", "qty", "mfg_code", "serial_number", "part_comments"]
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
inventory = find_by_id(row["id"]) || new
inventory.attributes = row.to_hash.select { |k,v| allowed_attributes.include? k }
inventory.save!
end
end


I end up with this error:
import error ruby

Thank you for any help!!

Answer

(...) inventory = (...) inventory.user_id = user_id inventory.save!

however it's better you send along the user rather than it's id:

controller: Inventory.import(params[:file], current_user)

model:

 def import(file, user)
  inventory = Inventory.new
  inventory.attributes = {}
  inventory.user = user
  inventory.save!
end