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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)