在模型中生成图像 URL - ActiveStorage

dar*_*ode 3 ruby ruby-on-rails ruby-on-rails-5 rails-activestorage

我有一个使用 ActiveStorage (Rails 5.2.0.rc2) 的简单模型,模型如下所示:

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
Run Code Online (Sandbox Code Playgroud)

然后在to_builder我想显示图像的永久 URL的方法中,我正在Rails.application.routes.url_helpers.url_for(image)按照 rails 指南(http://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files)中的建议进行尝试,但它引发了这个错误:

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

在我的应用程序中,我已经有了该default_url_options[:host]集合,但它不起作用,甚至写入url_for(image, host: 'www.example.com')或url_for(image, only_path: true)不起作用,因为它引发了另一个错误:wrong number of arguments (given 2, expected 1)

使用 activestorage 在模型范围内显示永久 URL 的正确方法是什么?

Jon*_*ado 9

rails_blob_path在模型和控制器中使用附件的方法

例如,如果您需要cover_url在模型中创建一个方法(例如),您应该首先包含url_helpers和使用rails_blob_path带有一些参数的方法。您可以在任何控制器、工作器等中执行相同操作。

完整示例如下:

class Event < ApplicationRecord

  include Rails.application.routes.url_helpers

  def cover_url 
    rails_blob_path(self.cover, disposition: "attachment", only_path: true)
  end

end
Run Code Online (Sandbox Code Playgroud)