I’m working on a new app for work. Basically, it’s just another app that lets people put up some info and an image to go with it. The difference to this one is that I’m storing information on glass plates, which each have a unique identifier that’s not an integer. I didn’t want to mess around with changing the primary key from id to something else, because later I’m going to be using it with some other tables. Instead, what I’d like to do is be able to show the image associated with the plate at a url that uses the unique identifier. So, instead of something like plates/12, I could download the info at sample/538-12122. Here’s what I did.

First, create a new controller called sample that has one action show. My show method is this:

def show
    @sample = Plate.find_by_incom_serial_number(params[:incom_serial_number])
    if @sample.nil?
          flash[:notice] = "Sample #{params[:incom_serial_number]} does not exist"
          redirect_to plates_path
    else
      render :layout => nil
    end
  end

Then I changed my routes file with:

match 'sample/:incom_serial_number' => 'sample#show', :as => :sample

Lastly, I created a sample/show view that just has one line.

<%= image_tag(@sample.scan.url(:original))%>

The other thing I did was change how the image was stored. I really like the paperclip gem, which made it easy for me to store the images in a directory named after the serial number instead of the id. This was done by making some changes in the plate model.

has_attached_file :scan,
                    :styles => {:thumbnail => '150x150>', :medium => '680x680>'},
                    :path => "#{Rails.root}/public/:attachment/:incom_serial_number/:style/:filename",
                    :url => "/:attachment/:incom_serial_number/:style/:filename"

 private
  
  # interpolate in paperclip
  Paperclip.interpolates :incom_serial_number do |attachment, style|
    attachment.instance.incom_serial_number
  end