Rails 3.1 asset pipeline outside view
I am trying to set CarrierWave's default url inside of the CarrierWave uploader. To do this, I would like to use the asset pipeline to do the following in uploaders/image_uploader.rb
:
def default_url
image_path('question_ma开发者_Python百科rk.png')
end
But it fails because: undefined method
image_path' for :ImageUploader`
Then I tried to add include ActionView::Helpers::AssetTagHelper
to uploaders/image_uploader.rb
but got this error: undefined local variable or method
config' for :ImageUploader`
Any idea how I can get the image_path
helper to work outside the view?
I asked a similar question here and concluded there is no way to get any *_path
or *_url
helpers working in models. I knew that it definitely shouldn't be done (violating MVC and so forth) but it seems it cannot be done at all...
My problem was setting the default_url
for a Paperclip attachment and I ended up setting it to the path I would give to image_tag
(simply 'image.png'
if image.png
is located in app/assets/images
or public/images
) and then using image_path
when accessing it. Would that work for you as well?
Not sure exactly what I was trying to do here, ended up working around it but in case anyone comes here wanting to add the _path or _url helpers in their model, do this:
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
I had a similar problem and I resolved it by doing the following in Rails 3.2.
I declared the following module:
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
I included the following helpers into the model where I wanted to use the asset_tag helpers
include Sprockets::Helpers::RailsHelper
include MyApp::AssetHelper
This allowed me to call the asset_tag helpers where I needed it.
精彩评论