とーますメモ

Ruby on Rails / Goなどの学習メモ

【Rails】Carrierwave(1.2.2)をActiveRecordと切り離して使用する方法を試してみた。

自分の用途としては、ただ画像を外部APIへ送信するため
ローカルDBに保存する必要がなかった。

しかし、多くのサイトを見るとCarrierwaveをActiveRecordと併せて使用する
サンプル例が多いため、自分で調べてみた。

インストール

Gemfileに追記

gem 'carrierwave'

インストール

$ bundle install

アップローダーの作成

ImageUploaderという名前のアップローダーを作成

$ rails g uploader image

アップローダーと画像保存用フィールドのマウント

多くの記事に載っているように
Carrierwaveを使用し、画像アップロードと連携させるためには
画像保存用のフィールドをCarrierwaveのアップローダーにマウントさせる必要がある。
しかしただ単に、以下のようにmount_uploaderを使用すると失敗する。

例)失敗例

class TestModel
  include ActiveModel::Model

  mount_uploader :image, ImageUploader
  ...
end

以下のエラーが表示される。

undefined method `mount_uploader' for TestModel:Class

公式サイトを見ると、以下のように書いてある。

If a Class is extended with this module, it gains the mount_uploader method, which is used for mapping attributes to uploaders and allowing easy assignment.

Module: CarrierWave::Mount — Documentation for carrierwave (1.2.2)

要は「CarrierWave::Mount」をextendすればmount_uploaderが使用できるようになるということ。
設定に成功した例は以下。

class TestModel
  include ActiveModel::Model
  extend CarrierWave::Mount

  mount_uploader :image, ImageUploader
  ...
end

画像を保存する

以下のサイトを見ると、以下のようにある。
Using Carrierwave uploader for tableless model in Rails (Example)

Based on carrierwave documentation you can use mount_uploader if your class extend CarrierWave::Mount module and your class will have capability to store a file using instance method store_(mounted_field)! or cache_(mounted_field)!

要は、store_(mounted_field)! または cache_(mounted_field)!で
画像をストアまたはキャッシュに保存できそうなことが書いてある。

しかし試してみたが、動作しなかった。
なぜだろう。。。しかし、以下のようにしたら動作した。

class TestModel
  include ActiveModel::Model
  extend CarrierWave::Mount

  attr_accessor :image
  mount_uploader :image, ImageUploader
  ...

  def test(params)
    self.image.store!(params[:image])
    # またはself.image.cache!(params[:image])
  end
end

もっと良い方法をご存じの方がいれば、
コメントくださいませ。


[参考]
Module: CarrierWave::Mount — Documentation for carrierwave (1.2.2)
ruby on rails - Carrierwave: Mount Uploader in non ActiveRecord inherited class - Stack Overflow
Using Carrierwave uploader for tableless model in Rails (Example)
How to use carrierwave without a model in rails? - Stack Overflow
CarrierWave使用時のTips | Gemの紹介 | DoRuby
Rails 超お手軽な画像アップローダー CarrierWave の使い方 | Workabroad.jp