How do I get full URL to an image in a Rails asynchronous mailer?

一笑奈何 提交于 2019-12-03 10:52:41

问题


I want to have emails I send out with ActionMailer contain images that link back to my app. In my development environment, for example:

<img src="http://myfullappurl.dev/assets/myimage.png">

I have this in my development.rb

config.action_controller.asset_host = 'myfullappurl.dev'
config.action_mailer.asset_host = config.action_controller.asset_host
config.action_mailer.default_url_options = { host: 'myfullappurl.dev', only_path: false }

But I can not get my mail templates to render a full URL in any of these way:

asset_path('myimage.png')
asset_path('myimage.png', only_path: false)
image_url('myimage.png')

A lot of similar questions on this topic are answered by doing something like this:

"#{request.protocol}#{request.host_with_port}#{asset_path('image.png')}"

But because my mails are sent asynchronously with Sidekiq, there is no request object like there would be if they were sent synchronously in a controller.

Is there an obvious thing I am missing, or do I have to fight against Rails to do this? I am using Rails 4, but I am sure that anything that works in 3.1/3.2 should do just fine.


回答1:


Well this is odd behaviour, but I've resolved this issue. It turns out that unless the action_mailer.asset_host starts with http:// then it will be ignored. There is a Regex in actionpack/lib/action_view/helpers/asset_url_helper.rb that defines a valid ActionMailer URI:

URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}

However, if you put a http:// in front of the action_controller.asset_host then you will end up with links to http://http://myfullappurl.dev

So to resolve it I had to add the following to my development.rb

 config.action_controller.asset_host = 'myfullappurl.dev'
 config.action_mailer.asset_host = 'http://myfullappurl.dev'

Just to be clear, this is Rails 4.0.0beta1 with the emails being sent asynchronously with Sidekiq, I am not sure if this affects Rails 3.




回答2:


I believe you need to set these in your config

config.action_controller.asset_host = 'http://localhost:3000' #Or your domain
config.action_mailer.asset_host = config.action_controller.asset_host



回答3:


in your environment file(i.e development.rb) :-

config.action_mailer.asset_host = 'http://localhost:3000' #Or your domain

in your mailer view file:-

<%= image_tag('image_name.jpg') %>

or

<img src="<%= image_url('image.jpg') %>" %>


来源:https://stackoverflow.com/questions/15490327/how-do-i-get-full-url-to-an-image-in-a-rails-asynchronous-mailer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!