สำหรับ Attachment_fu จะเป็น Plugin ของ Rails ที่ใช้สำหรับ Upload File นะครับ
โดยที่ตอนนี้จะเอามาใช้สำหรับ Upload ภาพ (ถ้าต้องการให้มีการทำ Image Processing เช่น การ Resize ภาพ ต้องทำการติดตั้ง Processor สำหรับการทำ Image Processing ก่อน เช่น rmagick)
ขั้นแรกก็ให้ Download Attachment_fu Plugin มาก่อน
หลังจากนั้นก็นำ Plugin ไปไว้ใน Project ที่ vendor/plugins
ส่วนการใช้งานก็เพิ่ม DB โดยจะประกอบด้วย
t.string :filename
t.string :path
t.string :content_type
t.integer :size
t.integer :width
t.integer :height
t.integer :parent_id
t.string :thumbnail
หลังจากนั้นก็ทำการบอก Model ให้รู้จักกับ Plugin
has_attachment :content_type => :image,
:storage => :file_system,
:min_size => 0,
:max_size => 1.megabytes,
:resize_to => ‘640×480′,
:processor => ‘Rmagick’,
:thumbnails => { :medium => ‘200×200′, :small => ‘80×80′, :tiny => ‘40×40′ }
ในที่นี้จะเป็นของภาพนะครับ โดยมีการใช้ Processor ของ Rmagick
การตรวจสอบก็สามารถใช้
validates_as_attachment
สำหรับการใช้งานในหน้า View ก็
ในการสร้าง (Upload) Files ให้ทำการเพิ่ม
:html => { :multipart => true }
เข้าไปใน form_for เช่น
<% form_for(@obj, :html => { :multipart => true }) do |f| %>
แล้วส่วนของ Select Image Field
<%= f.file_field ‘uploaded_data’ %>
ส่วนของหน้าในการ Show ให้ใช้
<%= image_tag(@obj.public_filename) %>
หรือ
<%= image_tag(@obj.public_filename(:medium)) %>
สำหรับภาพที่เป็น Medium (ตามที่ได้กำหนดไว้ใน Model)
ส่วนรายละเอียดอื่นๆ สามารถดูเพิ่มเติมได้ใน README ซึ่งจะมีคำอธิบายอยู่ด้วย