如何正确 return 从三元运算符到图像的路径(并显示它)

How to correctly return the path to an image from the ternary operator (and display it)

我是 rails 的新手。

我正在尝试在我的用户模型中实现以下方法

  def avatar_to_load
      self.picture ? self.picture.url : image_path("logo.png")
  end

如果User有图片则显示图片,没有则显示"logo.png",路径为app/assets/images/logo.png

我是 rails 的新手,所以我知道这可能非常简单。

输出是通过

    <%= image_tag user.avatar_to_load %>

这个很好用

    <%= image_tag user.image_path("logo.png") %>

所以我不确定为什么这个方法没有返回。

在image_path()之前添加self.?

  def avatar_to_load
      self.picture ? self.picture.url : self.image_path("logo.png")
  end

如果您想在模型中使用 image_path,您需要调用 ActionController::Base.helpers.asset_path("logo.png");

或者创建一个助手而不是 class 方法。

module UserHelper
  def avatar_to_load(user)
      user.picture ? user.picture.url : image_path("logo.png")
  end
end

并在您的观点中称呼它:<%= avatar_to_load(@user) %>

试试看

<%= image_tag (user.picture.present? ? user.picture.url : "logo.png") %>

或者

<%= image_tag (user.picture.present? ? user.picture.url : "logo.png"), :style => "width: 400px; height: 200px;" %>