Using image_url helper in model

1.2k Views Asked by At

I'm trying to use the image_url helper in my model. I also have an image_url property on the model(can't be changed). When I call image_url, the helper method it appears to be calling the method on the model. I get the error 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
3

There are 3 best solutions below

0
arieljuod On BEST ANSWER

image_url is a view helper, it should not be used inside the model, you should move that logic to a helper for the view

#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

In your view change user.public_image to public_image(user)

0
Matthieu Libeer On

I'll agree with arieljuod that this is a view concern. However, in case it's really needed for a dirty implementation, it is possible to do Object.new.extend(ActionView::Helpers::AssetUrlHelper).image_url('foo')

0
VinyLimaZ On

Yea, it's very right, you can't call on that scope! This isn't a method for a model. This is an ActionView helper method. https://apidock.com/rails/ActionView/Helpers/AssetUrlHelper/image_url

For what I'm seeing this isn't the right place to have this logic. Consider putting this in a decorator to abstract this non-business logic.