0

我正在尝试通过 CSV 批量上传。这是我的控制器的导入方法:

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

然后从我的 Item 模型中调用这个 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 %>

这是我的问题:当我检查数据库中的数据时,rails 正在分配自动递增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
4

1 回答 1

0

我不是 100% 确定,但我认为这可能有效。

首先,您必须根据此线程调整表结构以打开自动增量

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

如果这不起作用,请将以下行添加到您的模型中。

set_primary_key :id
于 2013-08-29T00:34:03.697 回答