Search code examples
ruby-on-railslocalemailboxer

Mailboxer gem's mailer results in ActionController::UrlGenerationError when no locale is passed


I am trying to use the Mailboxer gem to get a user-to-user messaging system in my Rails 4 app. However, I am getting the following error in my browser when sending messages:

ActionController::UrlGenerationError in Conversations#create

the culprit line is the following mailer template (new_message_email.html.erb):

Visit <%= link_to "this page", root_url %> and go to your inbox for more info.

and the reason is

No route matches {:action=>"index", :controller=>"rooms"} missing required keys: [:locale]

This is because my entire app's routes require a locale. My routes.rb looks like this:

Rails.application.routes.draw do
  get '' => redirect("/#{I18n.default_locale}")
  scope "/:locale", locale: /en|ja|ko/ do
    root 'rooms#index'
    resources :rooms
    # ... All my other routes here ...
  end
end

Interestingly, the console has the following error (which differs from the one in the browser):

ActionView::Template::Error (No route matches {:action=>"index", :controller=>"rooms"} missing required keys: [:locale]):
    14:       </p>
    15:     </blockquote>
    16:     <p>
    17:       Visit <%= link_to "this page", root_url %> and go to your inbox for more info.
    18:     </p>
    19:   </body>
    20: </html>

but I assume the template is not the problem - the real issue is that there's some previous call that is occurring that requires a locale to be passed, so root_url fails as it doesn't know which locale to use.

I am already passing the following in my application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :set_locale

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

  def default_url_options(options = {})
    { locale: I18n.locale }.merge options
  end
end

Does anyone know how I can fix this or how I can pass the locale to the mailer's root_url?

Also, please let me know if more code is required.

Thanks in advance :)


Solution

  • Bah, silly mistake! Specifying the locale seems to make it work:

    <%= link_to "this page", root_url(locale: :en) %>
    

    although ideally this setting should depend on the user's preferred language.