LoginSignup
5
6

More than 5 years have passed since last update.

【Rails】Paperclipで保存した画像のサムネイルの取得方法

Posted at

以下のようなモデルがあったときに、

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.integer :name
      t.attachment :icon
    end
  end
end
class User < ActiveRecord::Base

[:icon].each do |col|
        has_attached_file col , :styles => {:medium => "300x300", :thumb => "100x100"}, 
            :default_url => "./images/:style/missing.png",
            :url => "/images/:class/:attachment/:id_partition/:style/:filename"
        validates_attachment_content_type col,
            :content_type => ["image/png", "image/jpg", "image/jpeg"]
    end
end

サムネイルのディレクトリに保存した画像を表示したいです。

そんなときは、(上記例でいうと)iconの引数に":thumb"を付けてあげるとサムネイルのURLを返してくれます。

irb(main):003:0> User.first.icon(:thumb)
  User Load (0.4ms)  SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
=> "/images/users/icons/000/000/001/thumb/picture?1412045787"
sample.html.erb
<div>
    <%= image_tag(@user.icon(:thumb)) %>
</div>
5
6
0

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
5
6