・ Rubis: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ Système d'exploitation: macOS Catalina
Ce qui suit a été mis en œuvre.
・ Présentation mince ・ Introduction de Bootstrap 3 ・ Mise en œuvre de la fonction de publication
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 "importer", class: 'btn btn-success'
Recommended Posts