Tony Bagalini Tony Bagalini - 1 year ago 57
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
redirect_to root_url, notice: "Inventory imported."


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 = { |k,v| allowed_attributes.include? k }!

I end up with this error:
import error ruby

Thank you for any help!!

Answer Source

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

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

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


 def import(file, user)
  inventory =
  inventory.attributes = {}
  inventory.user = user!