LoginSignup
26
30

More than 3 years have passed since last update.

Railsのactive_storageとmini_magick使ってみる

Last updated at Posted at 2018-12-14

初めに

ActiveStorageという機能があってすごく便利だったのでやり方をまとめる

active_storage:install

active_storageを使うにはコンソールで

rails active_storage:install

を行う。
そうすると必要なファイルが作られるのでrails db:migrateする

保存、表示

モデルファイルに

has_one_attached :image

と書くか、もしくは

has_many_attached :images

と書く

has_one_attachedはそのモデルに一つの画像を紐づける場合に使ってhas_many_attachedは複数の画像を紐づけるときに使う。

もちろんhas_many_attached :imagesとかいたらimagesは配列としてわたるので

表示する際に

<%= image_tag(@post.images) %>

と書くとうまくいかないので

<% images.count.times do |i| %>
  <%= image_tag(@post.images[i]) %>
<% end %>

みたいにする。

has_one_attached :image の場合は一つしか画像を紐づけていないので

<%= image_tag(@post.image) %>

で画像を表示できる。

画像投稿

画像を投稿する際には

has_one_attached :image の場合は

投稿フォームに(postモデルに紐づけている場合)

<%= form_with(model: post, local: true) do |f| %>

  #省略

  <%= f.label :image %>
  <%= f.file_field :image %>

  <%= f.submit %>
<% end %>

でOK

コントローラーには

def create
  @post = Post.create(post_params)
end

private

def post_params
  params.require(:post).permit(:image,:何か,:何か)
end 

て感じで書いておけば大丈夫

has_many_attached :images の場合は

フォームの

<%= f.file_field :image %>

のところを

<%= f.file_field :images, multiple: true %>

書けばOK

コントローラーには

def create
  @post = Post.create(post_params)
end

private

def post_params
  params.require(:post).permit(images: [],:何か,:何か)
end 

みたいに書く

mini_magick

mini_magickを使えば画像にいろいろできる(語彙力....)

とりあえずGemfileに

gem 'mini_magick', '~> 4.8'

を追加する。 おそらくコメントアウトされてあるのでそれを使う

このmini_magickを使う場合image_magickを使う必要がある。

このimage_magickだがwindows環境でうまく使えなかった(自分だけかもしれないが....)

だがWSLでubuntuを使ってやってみたところうまくいった。

ubuntuでimage_magickをインストールするには

sudo apt-get install imagemagick

と書けばいける

mini_magickの使い方だが画像に対して

image.resize "100x100"
=>リサイズ
image.path 
=> 画像の名前表示

みたいな感じ

詳しくは
https://github.com/minimagick/minimagick

画像を表示する際にその画像をリサイズしたい場合は

post.rb

def thumbnail
  return self.image.variant(resize: '300x300').processed
end

とかいてview側で

<%= image_tag(@post.thumbnail) %>

と書いてやるようです。

active_storageのvalidation

アクティブストレージで保存する画像に対してバリデーションをするには

models/post.rbに

validate :image_type

def image_type
  if image.attached? && image.content_type.in?(%("image/jpeg image/png"))
    errors.add(:image, 'error message')
  elsif !image.attached?
    errors.add(:image, 'error message')
  end
end 

みたいにやるそうです。

参考にしたサイト

Dean Active Storage For Multiple Images | Validate & Resize | Ruby on Rails 5.2
https://www.youtube.com/watch?v=A23zCePXe74&t=617s

26
30
1

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
26
30