#009 File uploading by Carrierwave

| 31 minutes | file attachment upload carrierwave
介绍如何使用Carrierwave上传和处理附件。

Note: 视频前5秒钟有点模糊,后面就好了。新的转码工具有时候有点小bug,见谅。

安装所需要的gem

Gemfile
# Attachment
gem 'carrierwave'
gem 'rmagick'
gem 'mime-types'

Attachment Model:

app/models/attachment.rb
class Attachment < ActiveRecord::Base
  mount_uploader :attachment, AttachmentUploader

  belongs_to :attachmentable, :polymorphic => true

  validates :attachmentable, :presence => true
  validates :attachment, :presence => true


  before_save :set_attachment_attributes


  protected

  def set_attachment_attributes
    if attachment.present? && attachment_changed?
      self.content_type = attachment.file.content_type
      self.file_size = attachment.file.size
      self.file_name = attachment.file.original_filename
    end
  end
end

Attachment uploader:

app/uploaders/attachment_uploader.rb
class AttachmentUploader < CarrierWave::Uploader::Base

  include CarrierWave::RMagick
  include CarrierWave::MimeTypes

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process :set_content_type

  version :thumb, :if => :image? do
    process :resize_to_fit => [50, 50]
  end

  version :preview, :if => :image? do
    process :resize_to_fit => [80, 80]
  end

  protected

  def image?(new_file)
    new_file.content_type.include? 'image'
  end

end

Post model:

app/models/post.rb
has_many :attachments, :as => :attachment able

Form view:

app/views/posts/_form.html.erb
<div class="field">
    <%= file_field_tag :attachment%>
  </div>

Display view:

app/views/posts/_post.html.erb
<% post.attachments.each do |attachment| %>
    <%= image_tag attachment.attachment.url(:thumb) %>
  <% end %>
Similar Episodes