Read more

Rendering 404s for missing images via Rails routes

Arne Hartherz
April 27, 2017Software engineer at makandra GmbH

When you load a dump for development, records may reference images that are not available on your machine.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

Requests to those images may end up on your application, e.g. if a catch-all route is defined that leads to a controller doing some heavy lifting. On pages with lots of missing images, this slows down development response times.

You can fix that by defining a Rails route like this:

if Rails.env.development?
  scope format: true, constraints: { format: /jpg|png|gif/ } do
    get '/*anything', to: proc { [404, {}, ['']] }
  end
end

Images are (usually) served directly from public or assets and won't hit your controllers/routes, as long as the files exist. If files are missing, the request will be handled by the above route which instantly responds with an empty HTTP 404 response.

Posted by Arne Hartherz to makandra dev (2017-04-27 12:44)