Search code examples
ruby-on-railsmodel

asset_path helper erroring in method


I am creating a method on my model that I can use to return the URL to the correct logo, photo or a fallback image. My code is:

def image
    if photo1.attached?
        { url: photo1.url, alt: "Photo of #{full_name}" }
    elsif photos.any?
        photo = photos.first
        url = photo.url(:large_square)
        { url: url, alt: "Photo of #{full_name}" }
    else
        { url: url_for(asset_path "placeholder.svg"), alt: "Placeholder for #{full_name}" }
    end
end

But it's erroring with url_for and asset_path and i'm unsure how to resolve it?


Solution

  • You can Rails.application.routes.url_helpers and ActionView::Helpers::AssetUrlHelper

    You can include these modules to some class

    class MyClass
      include Rails.application.routes.url_helpers
      include ActionView::Helpers::AssetUrlHelper
    
      def my_url
        url_for(asset_path("placeholder.svg"))
      end
    end
    

    and MyClass.new.my_url will return path

    See also this answer:

    It is possible to use helpers with ActionController::Base.helpers or (and) with Rails.application.routes.url_helpers

    For example

    helpers = ActionController::Base.helpers
    url_helpers = Rails.application.routes.url_helpers
    
    helpers.link_to "Root_path", url_helpers.root_path
    # => "<a href=\"/\">Root_path</a>"
    

    But probably it is not good idea to define such methods in the models because they shouldn't know something about URLs and frontend assets. Maybe it's better to think about helpers or decorators for this purpose