2017-06-28 51 views
0

記錄我有我創建通過以下baserails教程,很少或沒有FUS功能紅寶石的應用程序,我試圖按照此tutorial到多個記錄上傳到數據庫中。這看起來很直接,我覺得我可以在幾分鐘內完成。紅寶石上傳CSV不顯示在數據庫

問題是,當我上傳CSV文件,我得到通知,我的上傳成功,首先,只有一條記錄被創建,其次是創建的記錄是空的。

我已經搜查,搜查

,嘗試其他教程,並最終有同樣的問題......我基本處於束手無策。請看下面我的代碼片段:Rails的服務器上

hospital.rb

class Hospital < ApplicationRecord 
    mount_uploader :image, ImageUploader 

    searchkick 

    has_many :reviews 

    #validates :name, :address, :phone, :image, presence: true 
    #validates :website, format: { with: /\Ahttps?:\/\/.*\z/, 
    #message: "must start with http:// or https://" } 
    #validates :phone, numericality: { 
    #only_integer: true, 
    #message: "must be land line(7 digits) or Gsm(11 digits)" 
    #} 
end 

hospital_controller.rb

class HospitalsController < ApplicationController 

    ... 

    def import 
     Hospital.import(params[:file]) 
    end 

    ... 

    def create 

     @hospital = Hospital.new(hospital_params) 

     respond_to do |format| 
     if @hospital.save 
      format.html { redirect_to @hospital, notice: 'Hospital was successfully created.' } 
      format.json { render :show, status: :created, location: @hospital } 
     else 
      format.html { render :new } 
      format.json { render json: @hospital.errors, status: :unprocessable_entity } 
     end 
     end 

    end 

    private 

    def hospital_params 
     params.require(:hospital).permit(:name, :address, :city_town, :state, :phone, :website, :safe_care, :jci, :cohsasa, :best_known_4, :image) 
    end 

end 

輸出

Started POST "/hospitals" for ::1 at 2017-06-22 12:58:09 +0100 
Processing by HospitalsController#create as HTML 
Parameters: {"utf8"=>"✓", 


"authenticity_token"=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxx==", 
    "hospital"=>{"name"=>"", 
"address"=>"", "city_town"=>"", "state"=>"", "phone"=>"", "website"=>"", 
"safe_care"=>"", "jci"=>"", "cohsasa"=>"", "best_known_4"=>""}, "file"=># 
<ActionDispatch::Http::UploadedFile:0x007fe064b78918 @tempfile=# 


<Tempfile:/var/folders/xh/hv6bwdzs3cx4ws9x42n3gsn00000gn/ 
T/RackMultipart20170622-80750-147ctbc.csv>, @original_filename="Test.csv", 
@content_type="text/csv", @headers="Content-Disposition: form-data; 
name=\"file\"; filename=\"Test.csv\"\r\nContent-Type: text/csv\r\n">, 
"commit"=>"Import CSV"} 
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? 
ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]] 
Can't verify CSRF token authenticity. 
(0.1ms) begin transaction 
(0.1ms) commit transaction 
(0.1ms) begin transaction 
SQL (0.5ms) INSERT INTO "hospitals" ("name", "address", "phone", "website", 
"created_at", "updated_at", "city_town", "state", "jci", "cohsasa", 
"best_known_4", "safe_care") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 
[["name", ""], ["address", ""], ["phone", ""], ["website", ""], ["created_at", 
2017-06-22 11:58:09 UTC], ["updated_at", 2017-06-22 11:58:09 UTC], 
["city_town", ""], ["state", ""], ["jci", ""], ["cohsasa", ""], 
["best_known_4", ""], ["safe_care", ""]] 
(0.8ms) commit transaction 
Hospital Store (170.8ms) {"id":53} 
Redirected to http://localhost:3000/hospitals/53 
Completed 302 Found in 188ms (Searchkick: 170.8ms | ActiveRecord: 1.9ms) 

回答

0

您的代碼行爲正是你如何寫它的行爲:

首先,只有一條記錄被創建 .. 。

沒錯。因爲你永遠不會調用:

Hospital.import(params[:file]) 

它在你的import動作,但你永遠不會從你的create行動調用它。當教程說:

步驟:3

添加塊在控制器

這並不意味着「任何你喜歡的老地方,它會奇蹟般地被稱爲」。你有實際呼叫邏輯。但是,你沒有。所以你的應用程序對CSV文件不做任何處理。這正是你告訴它如何處理CSV文件。

(另外,您Hospital類沒有進口類方法。所以,當你終於得到解決,以調用它,它會拋出一個錯誤。)

其次,創造紀錄是空的...

再次。就像你寫的那樣。

正如你可以在控制檯中看到,貴院PARAMS是空的:

Started POST "/hospitals" for ::1 at 2017-06-22 12:58:09 +0100 
Processing by HospitalsController#create as HTML 
Parameters: { 
    "utf8"=>"✓", 
    "authenticity_token"=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxx==", 
    "hospital"=>{ 
    "name"=>"", 
    "address"=>"", 
    "city_town"=>"", 
    "state"=>"", 
    "phone"=>"", 
    "website"=>"", 
    "safe_care"=>"", 
    "jci"=>"", 
    "cohsasa"=>"", 
    "best_known_4"=>"" 
    }, 
    "file"=>#<ActionDispatch::Http::UploadedFile:0x007fe064b78918 @tempfile=# 

所以,當你這樣做:

@hospital = Hospital.new(hospital_params) 

然後:

if @hospital.save 
    ... 
    else 
    ... 
    end 

嗯,你只是告訴你的應用程序創建一個空白記錄,並愉快地遵守(特別是因爲你已經刪除了所有的驗證)。

所以......寫Hospital.import方法(請參閱本教程的步驟4)是這樣的:

class Hospital < ApplicationRecord 

    mount_uploader :image, ImageUploader 

    searchkick 

    has_many :reviews 

    #validates :name, :address, :phone, :image, presence: true 
    #validates :website, format: { with: /\Ahttps?:\/\/.*\z/, 
    #message: "must start with http:// or https://" } 
    #validates :phone, numericality: { 
    #only_integer: true, 
    #message: "must be land line(7 digits) or Gsm(11 digits)" 
    #} 

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

    end 

說它在你的控制器,是這樣的:

def create 

     import if params[:file] # <= this here is the call to your import method 

     @hospital = Hospital.new(hospital_params) 

     respond_to do |format| 
     if @hospital.save 
      format.html { redirect_to @hospital, notice: 'Hospital was successfully created.' } 
      format.json { render :show, status: :created, location: @hospital } 
     else 
      format.html { render :new } 
      format.json { render json: @hospital.errors, status: :unprocessable_entity } 
     end 
     end 

    end 

加入您的再次進行驗證。而且您將會更加接近您的路途。

+0

謝謝你這個...也許我忘了補充,我是一個純粹的IT基礎設施Enginner嘗試學習新技能,所以很多你的術語雖然很熟悉,但我不確定如何繼續。我如何編寫Hospital.import方法並在我的控制器中調用它? –

+0

非常感謝你..現在它工作。 –

+0

很高興爲你效勞! – jvillian

0

試試下面的代碼在模型導入CSV INI分貝,並呼籲它在控制器:

def self.import(file) 
     spreadsheet = open_spreadsheet(file) 
     header = spreadsheet.row(2) 
     (3..spreadsheet.last_row).each do |i| 
     row = spreadsheet.row(i) #Hash[[header, spreadsheet.row(i)].transpose] 
     f1= from = row[0] 
     f2 = row[1] 
     f3 = row[2] 


     ModelName.create({f1: f1, ... }) 
     end 
end 
+0

你好Puneet18,我剛剛做過,情況是一樣的..數據庫中沒有記錄。 –

+0

上傳csv的地方? – puneet18

+0

打開鏈接https://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm並按照文件上傳步驟 – puneet18