Ruby on rails 通过CSV上载传递主键以创建操作

Ruby on rails 通过CSV上载传递主键以创建操作,ruby-on-rails,activerecord,csv,Ruby On Rails,Activerecord,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批量上传。以下是我从控制器导入的方法:

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 %>

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

首先,您必须根据这一点调整表结构,以实现自动递增

create_table(:table_name, :id => false) do |t|
  t.integer :id, :options => 'PRIMARY KEY'
end
如果这本身不起作用,请在模型中添加以下行

set_primary_key :id

您的
项目
模型是什么样子的?已使用项目模型更新。项目id存储在哪个模型中?我无法在我的应用程序中使用此功能。从我做的其他研究来看,如果应用程序变得更复杂,那么像这样试图对抗rails可能会导致问题。我继续在我的项目表中添加了一个
product\u code
bigint字段,并运行了与该字段的关联。现在看来还不错。
set_primary_key :id