2

I have a Rails 3.1 application where user-uploaded images are stored in the database. I'm using a dedicated path to serve these images through a Rails controller. Here is a portion of my routes.rb:

get "images/book_covers/:book_id", :controller => :book_covers, :action => :show
get "assets/book_covers/:book_id", :controller => :book_covers, :action => :show

Here is the code from the controller:

class BookCoversController < ApplicationController
  def show
    if @image = BookCover.find_by_book_id(params[:book_id])
      send_data(@image.image, :type => @image.content_type, :filename => "book_cover_#{@image.book_id}", :disposition => 'inline')
    else
      render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
    end
  end
end

This all works wonderfully in development mode (since asset pipelining is disabled), but when I try the app in production, I get (predictably, I suppose) the error: "ActionView::Template::Error (book_covers/61 isn't precompiled)". Here is the code that renders the image:

<%= image_tag book[:cover_image], :class => book[:cover_source].downcase %>

I'd rather not disable asset pipelining for the entire app, just for these images. How can I accomplish this (or am I just approaching this whole issue wrong)?

4
  • You use some assets_host configuration ?
    – shingara
    Mar 6, 2012 at 8:34
  • What return exactly the book[:cover_image] ?
    – shingara
    Mar 6, 2012 at 8:35
  • @shingara I am using the default assets_host configuration - in fact I have not customized any of the asset configuration values. book[:cover_image] returns a relative path (such as "book_covers/1" which the BookCoversController then handles).
    – Jack R-G
    Mar 6, 2012 at 19:47
  • I don't think the asset pipeline serves any purpose if you are pulling data from a DB. Serve them using a controller per @Wolfgang and keep them out of /assets. You can also write them into /public in the controller action so they'll be served on future requests by the web server. Mar 6, 2012 at 19:57

1 Answer 1

3

How about generating the image tag yourself without the asset pipeline, i.e. first name the route:

get "images/book_covers/:book_id", :controller => :book_covers, :action => :show, :as => :book_cover_image

and then in the template

<%= tag :img, :src => book_cover_image_path( book[:id], :class => book[:cover_source].downcase ) %>

Now the asset pipeline won't even know about your image, and your controller's show action will be called with the book's id as parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.