Skip to content

How to: Store the uploaded file size and content type

mbuckbee edited this page Aug 5, 2011 · 4 revisions

Simply add the relevant attributes to your model and introduce a before_save callback. In the example below, assume we have an assets table and a mounted AssetUploader.

class Asset < ActiveRecord::Base
  mount_uploader :asset, AssetUploader

  before_save :update_asset_attributes
  
  private
  
  def update_asset_attributes
    if asset.present? && asset_changed?
      self.content_type = asset.file.content_type
      self.file_size = asset.file.size
    end
  end
end
Clone this wiki locally