Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

前端 未结 15 2650
深忆病人
深忆病人 2020-11-27 10:34

I have been googling for about 90 minutes now and still don\'t have an answer to this. Where do I set default_url_options? I\'ve already set it for conf

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 11:35

    Set default_url_options to use your action_mailer.default_url_options.

    In each of your environment files (e.g. development.rb, production.rb, etc.) you can specify the default_url_options to use for action_mailer:

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

    However, these are not set for MyApp:Application.default_url_options:

    $ MyApp::Application.config.action_mailer.default_url_options
    #=> {:host=>"lvh.me", :port=>"3000"}
    
    $ MyApp::Application.default_url_options
    #=> {}
    

    That's why you are getting that error in anything outside of ActionMailer.

    You can set your Application's default_url_options to use what you defined for action_mailer in the appropriate environment file (development.rb, production.rb, etc.).

    To keep things as DRY as possible, do this in your config/environment.rb file so you only have to do this once:

    # Initialize the rails application
    MyApp::Application.initialize!
    
    # Set the default host and port to be the same as Action Mailer.
    MyApp::Application.default_url_options = MyApp::Application.config.action_mailer.default_url_options
    

    Now when you boot up your app, your entire Application's default_url_options will match your action_mailer.default_url_options:

    $ MyApp::Application.config.action_mailer.default_url_options
    #=> {:host=>"lvh.me", :port=>"3000"}
    
    $ MyApp::Application.default_url_options
    #=> {:host=>"lvh.me", :port=>"3000"}
    

    Hat tip to @pduersteler for leading me down this path.

提交回复
热议问题