【rails】 csv 파일의 데이터를 가져와 DB에 저장

8766 단어 RailsRails5

전제 조건



Rails 5.2.4.2

가져올 CSV 파일: house_data.csv

house_data.csv
first_name,last_name,city,num_of_people,has_child
Carolyn,Flores,London,2,Yes
Jennifer,Martinez,Cambridge,3,No
  ...

절차



컨트롤러/모델 만들기



terminal
rails g controller Houses
rails g model User first_name:string last_name:string city:string
num_of_people:integer has_child:string
rails db:migrate

ruby 표준 라이브러리 csv 추가



config/application.rb
require 'rails/all'
require 'csv'

gem 추가



csv 파일을 읽는 gem roo를 추가합니다.

Gemfile
gem 'roo'

terminal
$ bundle install

뷰에 CSV 업로드를 위한 필드 추가



app/views/houses/index.html.haml
      = form_tag import_houses_path, multipart: true do
        = file_field_tag :file
        = submit_tag "インポート"

  %table
    %thead
      %tr
        %th
          ID
        %th
          FirstName
        %th
          Lastname
        %th
          City
        %th
          num_of_people
        %th
          has_child
    %tbody
      - @houses.each do |house|
        %tr
          %td
            = house.id
          %td
            = house.first_name
          %td
            = house.last_name
          %td
            = house.city
          %td
            = house.num_of_people
          %td
            = house.has_child

컨트롤러에 액션 추가



app/controllers/houses_controller.rb
  def import
    House.import(params[:file])
    redirect_to houses_url
  end

라우팅 설정



config/routes.rb
Rails.application.routes.draw do
   resources :houses do
    collection { post :import }
  end
end

라우팅 확인



terminal
% rails routes
                   Prefix Verb   URI Pattern                                                                              Controller#Action
            import_houses POST   /houses/import(.:format)                                                                 houses#import
                   houses GET    /houses(.:format)                                                                        houses#index
                          POST   /houses(.:format)                                                                        houses#create
                new_house GET    /houses/new(.:format)                                                                    houses#new
               edit_house GET    /houses/:id/edit(.:format)                                                               houses#edit
                    house GET    /houses/:id(.:format)                                                                    houses#show
                          PATCH  /houses/:id(.:format)                                                                    houses#update
                          PUT    /houses/:id(.:format)                                                                    houses#update
                          DELETE /houses/:id(.:format)                                                                    houses#destroy


모델에 import 메소드를 기재



app/models/house.rb
class House < ApplicationRecord
  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      house = find_by(id: row["id"]) || new
      house.attributes = row.to_hash.slice(*updatable_attributes)
      house.save
    end
  end
  def self.updatable_attributes
    ["id", "first_name", "last_name", "city", "num_of_people", "has_child"]
  end
end


결과



localhost:3000/houses


참고문헌

좋은 웹페이지 즐겨찾기