Aalaa Abdel Mawla Aalaa Abdel Mawla - 5 months ago 29
Ruby Question

Set Default Image According To Gender - Carrierwave & Device

I use carrierwave for image uploading but since i have no access in the image_uploader.rb to the var 'current_user' of devise gem i cannot set a default picture based on gender when ever the picture url is nil(after create or update), is there a work out?

uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
def default_url
if (current_user.gender == "Male")
ActionController::Base.helpers.asset_path("fallback/" + [version_name, "male.PNG"].compact.join('_'))
else
ActionController::Base.helpers.asset_path("fallback/" + [version_name, "female.PNG"].compact.join('_'))
end
end
end

Answer

The solution is to add the two photos "male/female.png" under app/assets/images

Then in the helpers/application_helper create this method

def default_img(user)
  if user.avatar_url.nil?           
    if (user.gender == "Male")
         "male.PNG"
    else
        "female.PNG"
    end
  else
    user.avatar_url
  end
end

Then use this method with each img_tag