Url_for in email sent by rake team in rails 4
I have a rake challenge that sends out daily emails about player activity throughout the day. (See sample code below.) If I run PlayerActivityMailer.activity_report.deliver
in my console everything works fine. However, when I try to call the rake task, I get the following error:
rake aborted!
ActionView::Template::Error: arguments passed to url_for can't be handled.
Please require routes or provide your own implementation
After some research, I found that in Rails 4 they are completely nerfed ActionView::Helpers::UrlHelper.url_for
( http://apidock.com/rails/v4.1.8/ActionView/Helpers/UrlHelper/url_for - note the giant red minus sign under 4.0.2). If you look at the source, you see the error I see - it no longer accepts parameters. As far as I can tell, this functionality still exists in other url_for
s, such as ActionDispatch::Routing::UrlFor
. Additionally, the error message suggests enabling Rails.application.routes.url_helpers
.
What i tried
-
include ActionDispatch::Routing::UrlFor
both in the task rake (inside the task) and in the mailbox (both simultaneously and each separately) -
include Rails.application.routes.url_helpers
in the same locations and configurations including andUrlFor
.
The error still persists. My guess is that the pageview still insists on using the version ActionView::Helpers::UrlHelper
url_for
. I don't think I can actually include things in the views (which are sloppy looking and hacky, even if I could).
Sample code (heavily sanitized)
config / environtments / development.rb:
config.action_mailer.default_url_options = { host: 'localhost:3000' }
Lib / tasks / player.rake:
namespace :player do
task :activity => :environment do
PlayerActivityMailer.activity_report.deliver
end
end
App / senders / player_activity_mailer.rb:
class PlayerActivityMailer < ActionMailer::Base
def activity_report
@activities = PlayerActivity.all
mail(to: 'foo@bar.com', subject: 'activity report')
end
end
app / views / player_activity_mailer / activity_report.html.erb:
<% @activites.each do |activity| %>
Player: <%= link_to activity.player.name, player_url(id: activity.player.id) %>
...
<% end %>
I also have a Player model, resources :players
in my routes.rb file and a PlayerActivity class with a Player association.
I am currently using a (really terrifying) workaround @base_url = Rails.configuration.action_mailer.default_url_options[:host]
in my post action and "http://#{@base_url}/players/#{activity.player.id}"
in my view instead of the player_url part.
Help!
source to share