13
9

More than 5 years have passed since last update.

activeadmin+paperclipで画像管理機能導入メモ

Posted at

スクリーンショット_2015-02-28_23_09_54.png

スクリーンショット_2015-02-28_23_10_05.png

#メモなのでところどころ怪しいです

参考(詳しい)

前提

  • すでに activeadmin 導入済み( /admin が使える)
  • Imagemagickいれておく($ brew install imagemagick)

paperclip導入

Gemfile
gem 'paperclip'

Pictureモデル準備

$ bundle exec rails g picture name:string photo:attachment
$ bundle exec rake db:migrate
db/migrate/20150228120636_create_pictures.rb
class CreatePictures < ActiveRecord::Migration
  def change
    create_table :pictures do |t|
      t.string :name
      t.attachment :photo

      t.timestamps
    end
  end
end
app/models/picture.rb
class Picture < ActiveRecord::Base

  has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }
  validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }

end

ActiveAdminに追加

$ bundle exec rails g active_admin:resource Picture
app/admin/picture.rb
ActiveAdmin.register Picture do
  permit_params :id, :name, :photo

  index do
    column "ID", :id
    column "name", :name
    column "thumb", :photo do |obj|
      image_tag(obj.photo.url(:thumb))
    end
    actions
  end

  form multipart: true do |f|
    f.inputs Picture do
      f.input :name
      f.input :photo, as: :file, hint: image_tag(f.object.photo.url(:medium))

      f.actions
    end
  end

  show do |b|
    attributes_table do
      row :name
      row :photo do
        image_tag(b.photo.url(:medium))
      end
      row :url do
        b.photo.url
      end
      row :url_medium do
        b.photo.url(:medium)
      end
      row :url_thumb do
        b.photo.url(:thumb)
      end
    end
    active_admin_comments
  end

end

ほかのModelにも似たような手順で機能追加できそう。

13
9
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
13
9