Skip to content
Guilherme Otranto Aulicino edited this page Jun 13, 2013 · 1 revision

Using Imager with rails

Basic Notes

See picture.rb for a full example of use.

  • If you don't care about the name of image, just put picture.id in new name. Otherwise, you can store picture_file_id, or whatever, in a database and use it for file_id.

  • Remember that all fields are required. So if you don't have a polymorphic relation, use something like Product.class.model_name for collection, and product.id for album.

  • You may get validations errors on Imager Server. Be sure to validate:

    1. collection with /\A[a-z0-9]\z/i (Only letters and numbers)
    2. album with /\A[a-z0-9]\z/i (Only letters and numbers)
    3. new_name with /\A[a-z0-9\-]\z/i (Only letters, numbers, '-')
    4. If you don't use new_name, you should validate File.basename(file) with /\A[a-z0-9\-]+\.([a-z]{3,4})\z/i (Only letters, numbers, '-' and file extension)
  • If file is something like a .pdf, you will get Imager::ImagerError when posting the file.

Model

You can place this in a picture model for easy integration with activerecord:

  before_save do |picture|
    file       = picture.image_file.tempfile
    new_name   = picture.picture_file_id
    collection = picture.imageable.class.model_name
    album      = picture.imageable_id
    Imager::ServerInterface.post(collection, album, file, Picture.sizes, new_name)
  end

and declare:

  attr_accessor :image_file
  attr_accessible :image_file
  belongs_to :imageable, polymorphic: true # If you have a polymorphic

Controller

  @picture = Picture.new params[:picture]
  if @picture.save

View

  <%= f.file_field :image_file %>
Clone this wiki locally