【问题标题】:Ruby on Rails / HAML image_path not working in else condition?Ruby on Rails / HAML image_path 在其他条件下不起作用?
【发布时间】:2016-09-24 20:47:34
【问题描述】:

我目前正在使用 haml 进行一个关于 RoR 的项目,但我遇到了一个我以前从未见过的问题。

我有一个带有可选图片的“用户个人资料”。如果图像存在,我想显示图像,如果不存在,我显示一个占位符(存储在 assets =>“admin/avatar.png”中。所以,下面是我的示例代码:

-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;"}

第一个

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

不工作(并显示“丢失”),第二个实际工作。我对此有点迷茫。

有人吗?

谢谢。

【问题讨论】:

  • 你确定'missing'不是来自image_tag吗?
  • @user.image.url 等于什么?
  • @Maxime Bauer,您能否也发布您的用户模型代码,因为如果您的用户模型中定义了默认 url,那么它将始终执行第一个块而不是 else 块
  • 不,@user.image.url 等于“/system/users/images/000/000/003/original/lel.jpg?1474748997”例如,它的回形针属性。顺便说一句,我的 use rmodel 几乎是空的,我没有定义任何默认 url。

标签: ruby-on-rails ruby haml


【解决方案1】:

unless else 是一种代码味道

我建议的解决方案:

- 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;")

【讨论】:

  • 嗯,它穿了kd。顺便说一句,当我想链接资产图像时,我不知道为什么除非 else 条件会产生错误。太奇怪了,谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多