2017-06-28 6 views
0

fusがほとんどまたはまったくないbaserailsチュートリアルに続いて作成した機能的なRubyアプリケーションがあります。これは、tutorialに従ってデータベースに複数のレコードをアップロードしようとしました。 それはかなりストレートなように見え、私は分でそれを持つことができると思った。Rubyのcsvのアップロードでデータベースにレコードが表示されない

問題は、csvファイルをアップロードしたときにアップロードが成功したという通知が表示されます。まず、1つのレコードのみが作成され、2つ目は作成されたレコードが空です。

私は検索して検索し、他のチュートリアルを試して同じ問題を抱えてしまいました...私は基本的には賢明です。コードの下に

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

あなたのコードは、あなたが動作するようにそれを書かれている方法を正確に動作されています:デシベルINI csvファイルをインポートして、コントローラでそれを呼び出すためのモデルに

を第一に、1つのレコードのみがを作成します。..

イエップ。あなたが呼び出すことはありませんので:

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を参照)、このような何か:

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 

あなたを追加します。

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 

のようなものは、あなたのコントローラでそれを呼び出します妥当性確認が戻ってきます。そして、あなたはあなたの道にもっと近づくでしょう。

+0

ありがとうございました...たぶん私は追加するのを忘れました。私は純粋なITインフラストラクチャです。エンジニアは新しいスキルを学ぶように努力しています。どのように私はHospital.importメソッドを記述し、私のコントローラで呼び出すのですか? –

+0

ありがとうございました。 –

+0

それはあなたのために働いてうれしい! – jvillian

0

試してみてください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 

出力:以下の私のコードの抜粋を参照してください。

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

関連する問題