http://github.com/thoughtbot/paperclip/tree/master
最初からテーブルに含める場合
# migration ファイルに以下を追加
t.string :image_file_name, :image_content_type
t.integer :image_file_size
t.datetime :image_updated_at
t.string :image_remote_url
最後の image_remote_url は基本的には必要ないが、URLから画像アップロードしたいので、今回は追加しておく。
既存のテーブルに追加する場合
class AddImageColumnsToProducts < ActiveRecord::Migration
def self.up
add_column :products, :image_file_name, :string
add_column :products, :image_content_type, :string
add_column :products, :image_file_size, :integer
add_column :products, :image_updated_at, :datetime
end
def self.down
remove_column :products, :image_file_name
remove_column :products, :image_content_type
remove_column :products, :image_file_size
remove_column :products, :image_updated_at
end
end
モデルの設定
has_attached_file :image,
:styles => {:s => "150x150>", :m =>"320x320>", :l => "500x500>"},
:url => "/assets/products/:id/p_:style.:basename.:extension",
:path => ":rails_root/public/assets/products/:id/p_:style.:basename.:extension"
URLからのアップロードを可能にする場合は次も追加
# ====================================
# Paper Clip upload from url
# ====================================
attr_accessor :image_url
before_validation :download_remote_image, :if => :image_url_provided?
validates_presence_of :image_remote_url, :if => :image_url_provided?, :message => 'is invalid or inaccessible'
private
def image_url_provided?
!self.image_url.blank?
end
def download_remote_image
self.image = do_download_remote_image
self.image_remote_url = image_url
end
def do_download_remote_image
io = open(URI.parse(image_url))
def io.original_filename; base_uri.path.split('/').last; end
io.original_filename.blank? ? nil : io
rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...)
end
フォーム
<% form_for ([:admin, @page]), :html => {:multipart => true } do |f| %>
<%= f.file_field(:image) %>
...or provide a URL: <%= f.text_field :image_url %>
<% end %>
表示
<%= image_tag @foobar.image.url(:m) if @foobar.image? %>

0 件のコメント:
コメントを投稿