Rails - 如果用户没有头像,显示默认头像的最佳方式是什么? [英] Rails - What is the best way to display default avatar if user doesn't have one?

查看:45
本文介绍了Rails - 如果用户没有头像,显示默认头像的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,每次我需要显示用户的头像时,我都有 if 语句来检查他们是否上传了头像.我知道如果我的 html 中散落着这些语句,那绝对不是 DRY.

Right now, each time I need to display a user's avatar, I have if statements that check whether they uploaded an avatar or not. I know it's definitely not DRY if I have these statements littered through my html.

那么,找出要显示的图像的最佳方法是什么?

So, what's the best way to find out which image to display?

我正在使用 Carrierwave(Paperclip 由于某种原因对我不起作用)

I'm using Carrierwave (Paperclip didn't work for me for some reason)

推荐答案

尝试使用辅助方法.这应该可以解决您的后顾之忧.你的助手会像

Try using helper methods.That should solve your worries. Your helper would be like

def check_avatar(user)
     if user.image.nil?
       # return default image
    else
       #return user avatar
    end
end


您视图中的用法是
check_avatar(user)

这篇关于Rails - 如果用户没有头像,显示默认头像的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆