Reputation: 938
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?
Upvotes: 7
Views: 9798
Reputation: 874
rails_blob_path
for attachements in a models and controllersFor 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
Upvotes: 14
Reputation: 938
After investigate the only solution that I found is to use url_for
with a hash of options as suggested by @DiegoSalazar, then use the blobs
controller provided by activeresource and the correct params, ej:
Rails.application.routes.url_for(controller: 'active_storage/blobs', action: :show, signed_id: image.signed_id, filename: image.filename, host: 'www.example.com')
To be honest I think should be an easier way to access the permanent url of the image in the model scope, but for now is the only solution that I found.
Upvotes: 0