Bit of a strange scenario but let me explain. I have a view that needs to output a number of cars. The car photos are stored on Amazon S3. Some cars have photos whereas others do not. The ones that don't, need their image to display a locally stored placeholder graphic. The Car model has a boolean field to denote whether there is a photo for the car or not.
The part of the car partial is as follows:
<div class="car__photo-inner">
<img src="<%= car.photo_or_placeholder_url({size: :thumb, aspect: :square}) %>" />
</div>
The method in my Car model is as such:
def photo_or_placeholder_url(options = {})
if photo
photo_url(options)
else
asset_pack_path File.join(["media", "images", "placeholder.jpg"])
end
end
photo_url
just uses the options to grab the correct URL from Amazon S3 and works perfectly.
Where I am struggling is with getting the placeholder image to display. The placeholder is stored in /app/javascript/images.
Any suggestions?
Many thanks, Neil
Any suggestions?
Yes. Don't do it in the model. Models in Rails are already insanely overtaxed with responsibilities. And this is actually purely a view concern. Models really should only be concerned with the business logic and not the presentation if possible.
A helper method or a decorator:
module CarsHelper
def car_photo(car, **options)
url = if car.photo
car.photo_url(options)
else
"placeholder.jpg"
end
image_tag(url)
end
end
<div class="car__photo-inner">
<%= car_photo(car) %>
</div>
If the placeholder image is a developer concern just place it in app/assets/images
and use the conventions instead of fighting them.