Maxime Bauer Maxime Bauer - 2 months ago 15
Ruby Question

Ruby on Rails / HAML image_path not working in else condition?

I'm currently working on a project on RoR with haml, and i have an issue i have never saw before.

I have an "user profile" with an optional image. I want to show the image if it exists, if not, i show a placeholder (stored in assets => "admin/avatar.png". So, here is my sample code below:

-unless @user.image.nil?
=image_tag @user.image.url,class:"img-responsive img-circle",style:"width:150px;height:150px;margin:auto;"
-else
%img.img-responsive.img-circle{:src => image_path("admin/avatar.png"),style:"width:150px;height:150px;margin:auto;"}
%img.img-responsive.img-circle{:src => image_path("admin/avatar.png"),style:"width:150px;height:150px;margin:auto;"}


The first

%img.img-responsive.img-circle{:src => image_path("admin/avatar.png"),style:"width:150px;height:150px;margin:auto;"}


is not working (and shows "missing") and the seconde is actually working. I'm a bit lost with this.

Anyone ?

thanks.

Answer

unless else is a kind of code smell

A solution I'd propose:

- if @user.image.present?
 = image_tag(@user.image.url, class:"img-responsive img-circle",style:"width:150px;height:150px;margin:auto;")
- else
 = image_tag('admin/avatar', class:"img-responsive img-circle", style:"width:150px;height:150px;margin:auto;")