学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

【学習5.0】【MacOSX】画像アップロード(paperclip)

HomebrewでImageMagickをインストールします。


ターミナルで以下のコマンドを実行してください。
brew install imagemagick


記述追加 GemFile(82行目)

gem 'paperclip', '~> 5.1.0'



GemFile

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.7', '>= 5.0.7.1'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

# bulma
gem 'bulma-rails', '~> 0.7.4'
gem 'bulma-extensions-rails', '~> 1.0.30'

# デバイス
gem 'devise', '~>4.2'

# アバター
gem 'gravtastic'

# toastr
gem 'toastr-rails', '~> 1.0'

# 日本語化
gem 'rails-i18n'

# google認証
gem 'omniauth'
gem 'omniauth-google-oauth2'

# 管理ダッシュボード
gem 'activeadmin'

# 管理ダッシュボードのテーマ
gem 'active_skin'

#画像アップロード
gem 'paperclip', '~> 5.1.0'



コマンド
bundle


記述追加 config\environments\development.rb(3行目)

Paperclip.options[:command_path] = "/usr/local/bin/"



config\environments\development.rb

Rails.application.configure do

  #画像アップロード
  Paperclip.options[:command_path] = "/usr/local/bin/"

  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => 'public, max-age=172800'
    }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  config.file_watcher = ActiveSupport::EventedFileUpdateChecker

  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

  #Gメールの設定
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    enable_starttls_auto: true,
    authentication: "plain",
    user_name: 'win.rails.learn@gmail.com',
    password: 'vusopllqzbyvvahk'
  }

end



「config\initializers」フォルダに「paperclip_media_type_spoof_detector_override.rb」ファイルを新規作成します。


config\initializers\paperclip_media_type_spoof_detector_override.rb(新規作成したファイル)

require 'paperclip/media_type_spoof_detector'

module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
        false
    end
  end
end



コマンド
rails generate paperclip project image


更新
db\migrate\20200715015109_add_attachment_image_to_projects.rb
[5.0]の記述を追加して下さい。

class AddAttachmentImageToProjects < ActiveRecord::Migration[5.0]
  def self.up
    change_table :projects do |t|
      t.attachment :image
    end
  end

  def self.down
    remove_attachment :projects, :image
  end
end



コマンド マイグレーション適用
rails db:migrate


「app\models\project.rb」ファイルに以下の記述を追加します。


記述追加 app\models\project.rb(8,9行目)

    has_attached_file :image, styles: { medium: "680x300>", thumb: "170x75>" }
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/



app\models\project.rb

class Project < ApplicationRecord
    has_many :tasks

    validates :name, presence: true, length: { maximum: 50 }
    validates :content, presence: true, length: { maximum: 500 }
    validates :price, presence: true, numericality: { only_integer: true }

    has_attached_file :image, styles: { medium: "680x300>", thumb: "170x75>" }
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

end



「app\admin\projects.rb」ファイルの記述を更新します。


記述更新 app\admin\projects.rb

ActiveAdmin.register Project do

  permit_params :name, :content, :price, :image

  show do |t|
		attributes_table do
			row :name
			row :content
			row :price
			row :image do
				project.image? ? image_tag(project.image.url, height: '100') : content_tag(:span, "まだ画像がありません")
			end
		end
	end

	form :html => { :enctype => "multipart/form-data" } do |f|
		f.inputs do
			f.input :name
			f.input :content
			f.input :price
			f.input :image, hint: f.project.image? ? image_tag(project.image.url, height: '100') : content_tag(:span, "アップロードできるのは JPG/PNG/GIF 画像です。")
		end
		f.actions
	end

end





ブラウザ確認
http://localhost:3000/admin/projects


画像データが格納されるカラムが追加になっています。

画像格納カラム追加
画像格納カラム追加



プロジェクトの編集をすると画像を追加する項目が表示されます。

画像選択
画像選択



テストでプロジェクトの画像をアップロードしてみます。

画像を選択して更新
画像を選択して更新



無事画像をアップロードすることができました。

画像アップロード成功
画像アップロード成功