LoginSignup
0
0

More than 1 year has passed since last update.

Refileを使用した画像投稿機能の実装

Posted at

Refileとは

  • Refileを使用することで、画像の組み込みやファイルのアップロードを行うことができます。

実装

  • gemfileに下記を追記します。
gemfile
gem "refile", require: "refile/rails", github: 'manfe/refile'

記述後bundle installを行います。

$ bundle install
  • 画像を保存するカラムを追加します。
$ rails g migration AddImageIdToPosts image_id:string
  • データベースへ反映します
$ rails db:migrate
  • postテーブルにt.string "image_id"の1文が追加されていると思います。

  • ストロングパラメーターにimageカラムのデータを受けわたせるように追記します。

controller/posts_controller.rb
private
def post_params
  params.require(:post).permit(:location, :text, :image)
end
  • Refileがimageカラムにアクセスできるよう記述します。
model/post.rb
class Post < ApplicationRecord

  attachment :image

end
  • 新規投稿画面にボタンを作成します
  • 反映させたい部分に下記を追記します。
 <%= f.attachment_field :image %>
  • 画像を表示する部分には下記を記述します。
 <%= attachment_image_tag post, :image, format: 'jpeg', size: '100x100' %>
  • 実際に新規投稿を行ってみていただくと以下のエラーが出るかと思います。
Refile.secret_key = 'ここに英語とアルファベットの長文がでる'
  • 上記をすべてコピーし、config/initializers/application_controller_renderer.rbに貼り付けます。
config/initializers/application_controller_renderer.rb
# 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 = '先程の長文'

以上でRefileを使った画像投稿機能が作成出きました。

複数の画像を投稿する場合

  • 先程の機能だけでは画像1枚しか投稿できません。
  • 複数投稿を行う場合は新たにテーブルを作成する必要があります。

実装

  • gemの導入方法は先程と同様です

  • postカラムとimegeカラムを持ったpost_imagesテーブルを作成します。

  • モデルを編集します

app/models.post.rb
class Post < ApplicationRecord
  has_many :post_images, dependent: :destroy
  accepts_attachments_for :post_images, attachment: :image
end
app/models.post_image.rb
class PostImage < ApplicationRecord
  belongs_to :post
  attachment :image
end
  • コントローラーを編集
app/controllers/posts_controller.rb
 private
  def post_params
    params.require(:post).permit(:title, :content, post_images_images: [])
  end
end
  • ここでpost_images_images: []で配列で画像idを保存します。

  • 新規投稿画面に以下を追記

<td><%= f.attachment_field :post_images_images, multiple: true %></td>

multiple: trueで複数投稿ができるようになります。

  • viewの作成
  • attachment_image_tagの書き方
    <%= attachment_image_tag 保存先インスタンス名, :保存先カラム名, :fill, 幅, 高さ, format:'拡張子', fallback:"代替画像" %>
    画像を表示させたい部分に以下を追記
# 複数表示させる場合
<% @post.post_images.each do |image| %>
  <%= attachment_image_tag image, :image, class: "default_image" %>
<% end %>
# 1枚だけ表示させる場合
<% @post.post_images.first(1).each do |image| %>

これで画像を複数枚表示できるようになります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0