carrierwave

carrierwaveは、ファイルアップロード用のプラグインで、attachment_fuと同じようなやつ。

インストール

Gemfileに

gem 'carrierwave'

を追加

carrierwave用のファイルをジェネレータで作成する

rails generate uploader Image

以上のコマンドを実行すると

app/uploaders/image_uploader.rb

ファイルが作成される

モデルの作成

rails g migration Image

出来上がったマイグレーションファイルのupに以下を追加

create_table :images do |t|
  t.string :image_attachable_type
  t.integer :image_attachable_id
  t.string :image

  t.timestamps
end

モデルの設定

class Image < ActiveRecord::Base   mount_uploader :image, ImageUploader      belongs_to :image_attachable, :polymorphic => true
end

画像の保存先をファイルシステムに設定

app/uploaders/image_uploader.rb

ファイルを開き、

storage :file

を追加

アップロードしたファイルのサイズのバリエーションを設定

app/uploaders/image_uploader.rb

に以下の設定を追加

version :thumb do
  process :resize_to_fit => [50, 50]
end

[50,50]は画像サイズ
:resize_to_fit は画像の縮小方法で、縦か横の長いほうを50pxにして、縦横比維持したまま縮小
:scaleにすれば、縦横50pxで縮小

thumbのURLを取得するには

image = Image.first
image.thumb.url

とする