LoginSignup
2
3

More than 5 years have passed since last update.

[Rails] JSONをアップロードしてDBに保存する

Posted at

目標

ユーザーがアップロードしたJSONファイルをDBに保存する

やること

今回のやること

JSONファイルをアップロードする

JSONファイルをディコードする

テーブルの作成

DBに保存する

サンプルファイル

Sample.json
[{
  "text" : "hogehogeho",
  "name" : "Nick"
}, 
{
  "text" : "fugafugafugafuga",
  "name" : "Reversal"
}]

ルーティング

routes.rb
get '/upload', to: 'tweet#upload'
post '/import', to: 'tweet#import'

アップロード

まずViewを作ります

アップロード出来るファイルの拡張子をjsonに指定しています

upload.html.erb
<h1>気味の悪い拡張子のファイルをアップロード</h1>

<%= form_tag({controller: "tweet", action: "import", method: "post"}, {multipart: true}) do %>
  <div class="field"> 
    <%= file_field_tag :file, accept: ".json, text/json" %>
  </div>

  <div class="actions">
    <%= submit_tag "気味の悪い拡張子のファイルを読み込む"%>
  </div>
<% end %>

これでアップロード画面が出来ました

ディコード

次にアップロードしたJSONファイルをコンソールに表示出来るようにします

Controllerを作る

tweet_controller.rb
def upload

end

def import
  upload_file = params[:file].path
  json = ActiveSupport::JSON.decode(File.read(upload_file))
  json.each do |data|
    p data['text']
end

コンソールに以下が表示されると思います

hogehogeho
fugafugafugafuga

テーブルの作成

コンソールに表示することが出来たので今度はテーブルを作ります。

今回作るテーブルは以下です

Field Type
text string
name String
$ rails g model Tweet text:string name:string

忘れずマイグレーションもしておきましょう

$ rails db:migrate

DB保存

tweet_controller.rb
def import
  upload_file = params[:file].path
  json = ActiveSupport::JSON.decode(File.read(upload_file))
  json.each do |data|
    p data['text']

    # 下記を追記
    @tweet = Tweet.new(
      text: data['text'],
      name: data['name']
    )

    # 確認
    if @tweet.save
      p 'DB保存に成功'
    else
      p 'DB保存に失敗'
    end
end
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3