2013-08-29 36 views
0

我試圖通過CSV批量上傳。以下是我的控制器導入方法:通過主鍵通過CSV上傳創建操作

def import 
     params.permit(:id, :brand, :product, :details) 
     Item.import(params[:file]) 
     redirect_to root_url, notice: "Products imported." 
    end 

然後從我的項目模型中調用此self.import方法。

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

這是我上傳的形式:

<%= form_tag import_item_mgmt_index_path, multipart: true do %> 
    <%= file_field_tag :file %> 
    <%= submit_tag "Import" %> 
<% end %> 

這裏是我的問題:當我檢查在數據庫中的數據,鐵軌被分配一個自動遞增item_id代替item_id從我的CSV文件中傳遞。我需要爲我的應用程序分配這些特定的ID,但我不確定爲什麼我無法在創建時分配它們。看着參數,我甚至沒有看到我的item_id越過。幫幫我?提前致謝。

產品型號

class Item < ActiveRecord::Base 

has_many :inventory_items 
has_many :vendors, through: :inventory_items 
has_many :list_items 
has_many :shopping_lists, through: :list_items 

searchable do 
text :brand, :stored => true 
text :details, :stored => true 
text :product, :stored => true 
integer :id, :references, :stored => true 
end 
end 
+0

你的'Item'模型是什麼樣的? – zeantsoi

+0

更新了項目模型。 – settheline

+0

「item_id」存儲在哪個模型中? – zeantsoi

回答

0

我不是100%肯定,但我認爲這是可能的工作。

首先你必須根據這個thread調整表結構

create_table(:table_name, :id => false) do |t| 
    t.integer :id, :options => 'PRIMARY KEY' 
end 

打開自動遞增的。如果這並不在它自己的工作,下面一行添加到您的模型。

set_primary_key :id 
+0

我無法在我的應用中使用此功能。從我做的額外研究中,這聽起來像試圖對付rails這樣可能會導致問題,如果應用程序變得更復雜。我繼續前進,並在項目表中添加了一個'product_code' bigint字段,並將其關聯。似乎現在工作正常。 – settheline