2016-07-21 7 views
0

データのCSVをインポートしていますが、現在のユーザーデータをすべて削除してからインポートしたいと思います。すべての現在のユーザーのデータを新しくアップロードされたデータで効果的に置き換えます。私はそれを理解できません。どんな助けでも大歓迎です。ここで import csv既存のレコードをすべて削除してからインポートする

は..私はそれがすべてのユーザーデータだけではなく、現在のユーザーのデータを削除:(作業doestれ、持っているものであるcurrent_user.id

class Inventory < ApplicationRecord 
    belongs_to :user 

def self.import(file, user_id) 
    Inventory.destroy_all 
    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.user_id = user_id 
    inventory.save! 
    end 
end 
+0

ちょっとした注意:在庫が常に1人のユーザにインポートされる場合、 'import'は' User'クラスのインスタンスメソッドでなければなりません。 'Inventory'のクラスメソッドではありません。また、 'Inventory'か' InventoryItem'ですか? –

答えて

0

これを持つ行するのではなく、全体の在庫表を払拭します代わりに

Inventory.destroy_all 

が、これは現在のユーザーに属している在庫を破壊する:すべてのインベントリレコードだけでなく、現在のユーザーのを破壊する

Inventory.where(user_id: user_id).destroy_all 
関連する問題