簡體   English   中英

從Rails導入csv文件到oracle數據庫

[英]import csv file from rails to oracle database

我正在開發一個簡單的Web應用程序,並且通過“ activerecord-oracle_enhanced-adapter”和oci8連接了Oracle數據庫。

我有一個網頁,我想在其中選擇一個csv文件並將這些數據發送到oracle。

實際上,我可以從oracle數據庫中正確檢索條目,而沒有任何問題,當我通過webapp創建訂單時,也可以將帖子插入到oracle數據庫中。

這是我在models / commande.rb中的代碼:

class Commande < ApplicationRecord
   require 'csv'

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

控制器/ commandes_controller:

def import
   Commande.import(params[:file])
   redirect_to root_url, notice: "Activity Data Imported!"
end

視圖/ commandes / index.html.erb

<h4>Import pool orders</h4>
  <%= form_tag import_commandes_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import CSV" %>
<% end %>

路由器:

Rails.application.routes.draw do
  resources :commandes do
    collection {post :import}
  end
  resources :ressources

  root to: "commandes#index"
   # For details on the DSL available within this file, see 
 http://guides.rubyonrails.org/routing.html
end

當我選擇我的csv文件並單擊導入時,出現錯誤消息:ActiveModel :: UnknownAttributeError blabala表的字段。

我成功了一次(我不知道實際情況如何),並且收到了我的通知:“導入了活動數據”,但是所有數據都轉發到了我的oracle數據庫。

有誰有主意嗎?

我正在分享圖片。 易於查看所有信息。 如您所見,我嘗試使用另一個表“ users”。 我通過rails創建了表,並使用db:migrate獲取到oracle。 與下面描述的錯誤相同:

屏幕截圖錯誤

CSV.foreach(file.path, headers: true) do |row|
  Commande.create! row.to_hash
end

好吧,您的代碼應該可以正常運行。 某種程度上,它錯誤地輸出了行。 您有哪個版本的Ruby?

從圖片中可以看到,正在發生的事情是它提供了一個{ "user_id;name" => "3;Laure" }類的哈希,其中應為{ 'user_id': "3", 'name': "Laure" }

因為您的模型沒有列"user_id;name" ,所以出現了錯誤,它有兩列,一個user_id另一個name

因此,您打開的CSV格式錯誤或紅寶石版本已過時。

您可以通過直接將csv列映射到模型上的字段來完成此工作,例如

CSV.foreach(file.path, headers: false) do |row|
  split_row = row.split(';')
  Commande.create!(user_id: split_row[0], name: split_row[1])
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM