简体   繁体   中英

rake task and action_mailer.default_url_options

When I try to use ActionMailer from rake task I'm getting this error:

ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host] , or set :only_path to true

In my development.rb I have the following line:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Moreover, if I put in development.rb this:

config.action_mailer.default_url_options[:host] = 'localhost:3000'

rake task works fine, but server crashes with this:

config/environments/development.rb:20:in block in ': undefined method []=' for nil:NilClass (NoMethodError)

If I do this:

config.action_mailer.default_url_options = {}
config.action_mailer.default_url_options[:host] = 'localhost:3000

rake task doesn't work again.

I'm confused, any suggestions?

UPD i don't think that code will help, but here it is, it's that simple:

rake task:

 task :send_newsletter => :environment do
    Receiver.all.each { |receiver|
      NewsletterMailer.newsletter(receiver).deliver
    }
  end

mailer:

  def newsletter(receiver)
    @receiver = receiver

    mail(to: receiver.email, subject: "newsletter") do |format|
          format.html 
    end
  end

and the view with some link_to xxx_url lines, apparently which causing the error

ruby version 2.4.1

rails 5.1.3

rake 12.0.0 (but also tried 12.3.0 with no difference)

Try the following, that should work

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

Update

I don't know what is the ideal solution for this? but I have tested and it working for me

Rails.application.routes.default_url_options = config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

This also work

Rails.application.routes.default_url_options = Rails.application.config.action_mailer.default_url_options

This solution based on this link

And another one is

Rails.application.routes.default_url_options[:host] = '???'

This goes in each environment file - development.rb , test.rb and production.rb (and more if you have them) with the corresponding hostname in each one

Based Link

Hope it will help

solved with this line added to rake task. based on fool-dev's answer

Rails.application.routes.default_url_options = Rails.application.config.action_mailer.default_url_options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM