Rails 3.1资产管道在视图之外

3
我正在尝试在CarrierWave上传程序中设置默认的url。为此,我想在uploaders/image_uploader.rb中使用asset pipeline来执行以下操作: def default_url image_path('question_mark.png') end
但是它失败了,因为:undefined method 'image_path' for :ImageUploader 然后我尝试将include ActionView::Helpers::AssetTagHelper添加到uploaders/image_uploader.rb中,但出现了这个错误:undefined local variable or method 'config' for :ImageUploader 有任何想法如何使image_path助手在视图之外工作吗?
3个回答

1

我曾经在这里提出了类似的问题,并得出结论,无法在模型中使用任何*_path*_url助手。我知道这绝对不应该被做(违反MVC等),但似乎根本无法实现...

我的问题是设置Paperclip附件的default_url,最终我将其设置为我会给image_tag的路径(如果image.png位于app/assets/imagespublic/images中,则为'image.png'),然后在访问时使用image_path。这对你也有用吗?


0

我曾经遇到过类似的问题,我在Rails 3.2中通过以下方式解决了它。

我声明了以下模块:

module MyApp::AssetHelper
  def config
    @config ||= ActionController::Base.config
    @config.asset_host = 'http://whereveryouhostyour.assets' #not needed if you have this defined in your environment file
    @config
  end

  def controller
    ActionController::Base
  end
end

我将以下辅助函数包含在我想使用 asset_tag 辅助函数的模型中

include Sprockets::Helpers::RailsHelper
include MyApp::AssetHelper

这使我能够在需要时调用asset_tag助手。

0

不太确定我在这里到底想要做什么,最终绕了个弯路,但是以防有人想要在其模型中添加 _path 或 _url 助手,请执行以下操作:

class Post < ActiveRecord :: Base
  include Rails.application.routes.url_helpers

  # This is so you can use _url params
  # you'll need to define the host in your config for it to work though
  default_url_options[:host] = Rails.configuration.host

  # ...

end

Rails.application.routes.url_helpers 应该用于生成 routes.rb 中定义的 URL,而不是图像 URL。 - Guilherme Garnier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接