camdixon
camdixon

Reputation: 882

Rails If - Else Statement image_url to check existence

<div class="img-container">
  <%= if @user.image_url.present? %>
    <%= image_tag @user.image_url(:main).to_s %>
  <%= end %>
</div>

I am using rails 4, and carrier wave to upload photos as mentioned in the rails casts. So I have a column in my db that is called "image", and the above code works without the if statement. When I use the @user.image_url(:main).to_s and it has an image it properly shows the image in the container. I want to upload a standard photo when the user does not provide one. It's located in my assets/images folder.

How can I get the if statement to detect if there is photo present or not in the column image? I have to use image_url if showing the user uploaded photo. Not just image to display the image, and the .to_s is a safety net. Any thoughts or answers?

Thanks!

Thanks to the accepted answer, I did use the suggested carrier wave solution for Rails 4 which is recommended for 3.1 and above. This post helped me get it corrected: Default URL not loading with Carrierwave in Rails

Upvotes: 1

Views: 435

Answers (2)

Antoine
Antoine

Reputation: 1344

For Rails 5 the one that worked for me is

ActionController::Base.helpers.resolve_asset_path("logos/smthg.png")

returns nil if the asset is absent and the asset path if present

👍

Upvotes: 1

pdobb
pdobb

Reputation: 18037

Specifying a default url with CarrierWave should do the trick. This allows for a fallback if no image is currently present.

Example:

def default_url
  ActionController::Base.helpers.asset_path "fallback/main/default.jpg"
end

Upvotes: 2

Related Questions