【问题标题】:Rails 3.1 asset pipeline outside viewRails 3.1 资产管道外观
【发布时间】:2011-11-23 06:23:23
【问题描述】:

我正在尝试在 CarrierWave 上传器中设置 CarrierWave 的默认网址。为此,我想使用资产管道在uploaders/image_uploader.rb 中执行以下操作: def default_url image_path('question_mark.png') 结束

但它失败了,因为:undefined methodimage_path' for :ImageUploader`

然后我尝试将include ActionView::Helpers::AssetTagHelper 添加到uploaders/image_uploader.rb 但收到此错误:undefined local variable or methodconfig' for :ImageUploader`

知道如何让image_path 助手在视图之外工作吗?

【问题讨论】:

    标签: ruby-on-rails-3.1 asset-pipeline


    【解决方案1】:

    我问了一个类似的问题 here 并得出结论,没有办法让任何 *_path*_url 助手在模型中工作。我知道它绝对不应该完成(违反 MVC 等等),但似乎根本无法完成......

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

    【讨论】:

      【解决方案2】:

      不确定我究竟想在这里做什么,最终解决了这个问题,但如果有人来这里想在他们的模型中添加 _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
      【解决方案3】:

      我遇到了类似的问题,我通过在 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 助手。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-04
        • 2011-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多