refileを使った画像投稿機能導入方法
ターミナルでImageMagickのインストール
#上から順番に実行する(実行するディレクトリは、どこでもいい。) sudo yum -y install libpng-devel libjpeg-devel libtiff-devel gcc cd wget http://www.imagemagick.org/download/ImageMagick.tar.gz tar -vxf ImageMagick.tar.gz ls cd ImageMagick-x.x.x-xx ./configure make sudo make install
rails側の設定
gem
# 画像投稿用gem gem "refile", require: "refile/rails", github: 'manfe/refile' # 画像加工用(サイズ調整など)gem gem "refile-mini_magick"
bundle
データベース
以下のように、画像を保存したいテーブルにimage_idを追加する。
create_table "posts", force: :cascade do |t| : : #image_idと書いているが、実際は文字列。(後述) t.string "image_id" : : end
モデル
attachment :image
投稿
: : <%= f.attachment_field :image %> : :
とりあえず、rails sで投稿すると以下のような画面が出る。 ここに書いているキーをconfigに貼り付ける。
# Be sure to restart your server when you modify this file. # ActiveSupport::Reloader.to_prepare do # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # ) # end Refile.secret_key = '3238beb2f9945d440d0140ba9a28ace320d1a8a67178697999696c08e6655867768c5b002538b2b5e6ec4f0bbdfb03b06aa0ee7679999bd58bfeb4bdd5ead8a3'
保存
def create Post.new(post_params).save end : : def post_params params.require(:post).permit(:title, :body, :image) end
〜参考〜 投稿時、binding.pryでparamsを覗いてみる。
[1] pry(#<PostsController>)> post_params => <ActionController::Parameters { "title"=>"aaaa", "body"=>"aaaaaa", "image"=>#<ActionDispatch::Http::UploadedFile:0x00007fb0b00af588 @tempfile=#<Tempfile:/tmp/RackMultipart20210202-14306-orj859.jpeg (closed)>, @original_filename="54b7e1f981b7df7c817af48d1b96ad5e_400x400.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"list[image]\"; filename=\"54b7e1f981b7df7c817af48d1b96ad5e_400x400.jpeg\"\r\nContent-Type: image/jpeg\r\n"> } permitted: true>
保存後、SQLでimage_idを覗いてみる。
rails dbconsole
sqlite> SELECT image_id FROM posts; /* 以下のように画像が文字列で保存されている事がわかる。 */ /* 1枚目(コメント) */ d64ff76c065fc7b98c995e2c07611856ca20b2caae61632c2ac0f201c878 /* 2枚目(コメント) */ c675db59c69164df9a1f487146f676d2f32827943ed346caf443f01e7fa7v : :
表示
: : <%= attachment_image_tag @post, :image, :fill, 300, 300, format: 'jpeg' %> : :
以上で画像が表示されるはず。