如何从Rails控制器获取S3资产的路径

时间:2014-12-22 19:51:41

标签: ruby-on-rails amazon-s3 paperclip asset-sync

我的设置

我正在使用Rails 3,asset_sync和paperclip。

  • 当我在本地计算机上开发时,我希望通过资产管道提供资源
  • 在制作中,我希望资源来自 S3

我的问题

如何从Controller / Model /中访问资产路径? (如果我在视图中使用image_path("favicon.ico"),则会获得相同的网址)

我已经看到了无数的SO问题,其中接受的答案建议使用ActionController::Base.helpers.asset_path("favicon.ico")。那很好,但是,当我在生产中尝试它时,我得到一个指向我的生产服务器的URL,而不是S3。

我在生产HAML中添加了一段测试代码来演示问题:

%link{:rel => "image_src", :href => image_path("test.png")} %link{:rel => "image_src", :href => ActionController::Base.helpers.image_path("test.png")}

...生成HTML:

<link href='http://mybucket.s3.amazonaws.com/assets/test-2cfd63058597b0c73221f3c1988c121e.png' rel='image_src'> <link href='/assets/test-2cfd63058597b0c73221f3c1988c121e.png' rel='image_src'>

所以,我认为 ActionController :: Base.helpers.image_path 不是解决问题的正确方法。

我也看到许多答案说应该使用view_context。但是,当我需要URL时,我没有控制器的实例,所以这种方法对我来说也不起作用。

更多背景(如果您有兴趣)

我想要实现的是从S3提供Paperclip默认图像。

has_attached_file :logo, :styles => { ... }, :default_url => # Here, I need the URL that points to S3, if this is run in production.

我不想将URL硬编码为指向我的S3存储桶,因为我想在开发时从本地计算机上提供文件(如此处所示:https://github.com/thoughtbot/paperclip/issues/1092)< / p>

1 个答案:

答案 0 :(得分:1)

看起来像这里描述的问题:https://github.com/rails/rails/issues/10051似乎在Rails 4中使用https://github.com/rails/rails/pull/12622修复了。

第一个讨论描述了使用Rails 3初始化程序的可能解决方法:

class ActionController::Base
  def self.helpers
    @helper_proxy ||= begin
      proxy = ActionView::Base.new
      proxy.config = config.inheritable_copy
      proxy.extend(_helpers)
    end
  end
end