・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
The following has been implemented.
・ Slim introduction ・ Introduction of Bootstrap3 ・ Implementation of posting function
Gemfile
#Postscript
gem 'roo'
Terminal
$ bundle
application.rb
require_relative 'boot'
require 'rails/all'
require 'csv' #Postscript
Bundler.require(*Rails.groups)
module Bookers2Debug
class Application < Rails::Application
config.load_defaults 5.2
end
end
book.rb
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
book = find_by(id: row["id"]) || new
book.attributes = row.to_hash.slice(*updatable_attributes)
book.save!(validate: false)
end
end
def self.updatable_attributes
['id', 'title', 'body']
end
book = find_by(id: row["id"]) || new
book.attributes = row.to_hash.slice(*updatable_attributes)
book.save!(validate: false)
def self.updatable_attributes
['id', 'title', 'body']
end
books_controller.rb
def import
Book.import(params[:file])
redirect_to books_path
end
routes.rb
resources :books do
collection { post :import }
end
slim:books/index.html.slim
= form_tag import_books_path, multipart: true do
= file_field_tag :file
br
= submit_tag "import", class: 'btn btn-success'
Recommended Posts