技術系ブログ

とにかく小ネタで

画像のアップロード機能(Shrine)まとめ 

こんばんは今現在学習用にポートフォリオを作成中です

Shrineを使ってみたのでまとめました

 

そのまま画像を表示するまで

①shine gemを導入
gem 'shrine'

 

②初期設定をします。

参照:https://github.com/shrinerb/shrine#quick-start

設定するファイルの場所はconfig/initializers/ です

$ touch config/initializers/shrine.rb で作ります

require "shrine"
require "shrine/storage/file_system"


Shrine.storages = {
    cache: Shrine::Storage::FileSystem.new("public"prefix: "uploads/cache"),
    store: Shrine::Storage::FileSystem.new("public"prefix: "uploads/store")}


Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data

shrineの特徴として必要な昨日をpluginでどんどん追加する感じでやっていきます

 pluginの解説として

参照:https://shrinerb.com/#plugins

③追加したいモデルにimage_data属性を追加

私の場合はpostモデルなので

rails g migration add_image_to_posts  image_data:text

(ここでデータ型はtext出ないといけない。)

class AddImageDataToPosts < ActiveRecord::Migration[5.2]
  def change
    add_column :posts:image_data:text
  end
end

そして rails db:migrate

④ImageUploaderモデルを実装

記述する場所は app/uploaders/image_uploader.rb

まずはフォルダ作成 mkdir app/uploaders

次にファイルを作成  touch  app/uploaders/image_uploader.rb

下記のように記述する

class ImageUploader < Shrine
  # plugins and uploading logic
end
⑤Postモデル側の編集

 

class Post < ApplicationRecord
    include ImageUploader[:image]
end

 image_data属性で作成しましたが[:image]と書かなくてはいけません。

⑥Strong parameterに:imageを追加

ここでも:imageと書く

private

    def post_params                
      params.require(:post).permit(:title:content,:image)
    end
⑦viewファイルの編集

まずはform側

    .field
        = f.label :image_data
        = f.hidden_field :imagevalue: @post.cached_image_data
        = f.file_field :image

そしてshow側

= image_tag  @post.image_url

 

これでひとまずアップロードした大きさと同じ状態で表示されます

 画像のリサイズ

は、また明日