在模型中使用 image_url 助手

Using image_url helper in model

我正在尝试在我的模型中使用 image_url 助手。我在模型上也有一个 image_url 属性(无法更改)。当我调用 image_url 时,辅助方法似乎是在调用模型上的方法。我收到错误 wrong number of arguments (given 1, expected 0)

 def public_image
    if self.avatar && photo_public?
      self.avatar.remote_url
    else
      image_url '/client/src/assets/images/icons/anon-small.svg'
    end
  end

image_url 是视图助手,不应在模型内部使用,您应该将该逻辑移至视图助手

#application_helper.rb
def public_image(user)
  if user.avatar && user.photo_public?
    user.avatar.remote_url
  else
    image_url '/client/src/assets/images/icons/anon-small.svg'
  end
end

在您看来,将 user.public_image 更改为 public_image(user)

我同意 arieljuod 的观点,这是一个观点问题。但是,如果脏实现确实需要它,则可以执行 Object.new.extend(ActionView::Helpers::AssetUrlHelper).image_url('foo')

是的,非常正确,你不能调用那个范围! 这不是模型的方法。 这是一个 ActionView 辅助方法。 https://apidock.com/rails/ActionView/Helpers/AssetUrlHelper/image_url

就我所见,这不是拥有此逻辑的正确位置。考虑将其放在 decorator 中以抽象此非业务逻辑。