2009/12/14

Rails Paperclip

Ruby on Rails の画像アップロードプラグイン(?) Paperclip の使用メモ。

サムネイルつくるのに ImageMagick が必要なので別途インストールしておく。

参考

インストール

script/plugin install git://github.com/thoughtbot/paperclip.git

今回は新規にモデルを作ってみる。 Paperclip は次の4つのカラムを必要とする。

  • avatar_file_name:string
  • avatar_content_type:string
  • avatar_file_size:integer
  • avatar_updated_at:datetime
script/generate rspec_model UserProfile name:string self_introduction:text avatar_file_name:string avatar_content_type:string avatar_file_size:integer avatar_updated_at:datetime user:references
rake db:migrate
rake db:migrate RAILS_ENV=test

User と UserProfile のリレーションを設定。

class User < ActiveRecord::Base
has_one :user_profile
...
end

モデルに has_attached_file(name, options = {}) を追加する。 options には次が指定可能。

  • url ファイルの場所。ディレクトリも URL も指定可能。デフォルトは "/system/:attachment/:id/:style/:filename"
  • default_url 画像がない場合に表示する画像の場所。
  • styles サムネイルの設定ハッシュ。
  • default_style url メソッドで引数を省略した場合の値。 styles ハッシュのキーを指定する。
  • whiny post_process でエラーが発生した場合にエラーをあげるか。デフォルト true
  • convert_options convert コマンドに渡すオプションのハッシュ。キーは styles ハッシュのキー。:all をキーとしたものは全てに適用。 http://www.imagemagick.org/script/convert.php を参照。
  • storage ファイルを保存するストレージ。 :filesystem か :s3。デフォルトは :filesystem。
class UserProfile < ActiveRecord::Base
belongs_to :user
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end

UserProfile のコントローラを作成。

script/generate rspec_controller UserProfiles show new edit

config/routes.rb に追加。

  map.resource :user_profile

登録のビュー。 :html => { :multipart => true } が必要。

<h1>ユーザプロフィール作成</h1>
<% form_for@user_profile, :html => { :multipart => true } do |f| %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :self_introduction %>
<%= f.text_field :self_introduction %>
</p>
<p>
<%= f.label :avatar %>
<%= f.file_field :avatar %>
</p>
<p>
<%= f.submit '保存' %>
</p>
<% end %>

コントローラ。

# -*- coding: utf-8 -*-
class UserProfilesController < ApplicationController
def show
@user = User.find(current_user)
@user_profile = @user.user_profile
end

def new
@user_profile = UserProfile.new
end

def create
@user = User.find(current_user)
@user_profile = UserProfile.create(params[:user_profile])
@user.user_profile = @user_profile
if @user.save
flash[:notice] = 'ユーザプロフィールを作成しました。'
redirect_to @user_profile
else
render :action => :new
end
end
end

0 件のコメント: