Search code examples
ruby-on-railsrubyruby-on-rails-5rails-activestorage

Generate image URL in model - ActiveStorage


I have a simple model using ActiveStorage (Rails 5.2.0.rc2), the model looks like this:

class Vacancy < ApplicationRecord
  has_one_attached :image

  validates_presence_of :title

  def to_builder
    Jbuilder.new do |vacancy|
      vacancy.call(self, :id, :title, :description, :created_at, :updated_at)
      vacancy.image do
        vacancy.url image.attached? ? Rails.application.routes.url_helpers.url_for(image) : nil
      end
    end
  end
end

Then in the to_builder method I want to show the permanent URL for the image, I'm trying with Rails.application.routes.url_helpers.url_for(image) as suggested in the rails guides (http://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files) but it raises this error:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

In my application I already have the default_url_options[:host] set but it doesn't work, even writing url_for(image, host: 'www.example.com') or url_for(image, only_path: true) doesn't work either as it raises another error: wrong number of arguments (given 2, expected 1)

What is the correct way to show the permanent URL in the model scope using activestorage?


Solution

  • Use the method rails_blob_path for attachements in a models and controllers

    For example, if you need create a method (e.g. cover_url) in a model, first you should include url_helpers and after use method rails_blob_path with some parameters. You can do the same in any controller, worker etc.

    Complete example below:

    class Event < ApplicationRecord
    
      include Rails.application.routes.url_helpers
    
      def cover_url 
        rails_blob_path(self.cover, disposition: "attachment", only_path: true)
      end
    
    end