Question

I have removed gem routing-filter from my Rails 3.2.13 application in preparation to upgrade it to Rails 4. The author(s) have a beta version for Rails 4 but I could never get it to work. I have implemented the normal Rails process for localization/internationalization. The last issue I need to resolve is a link_to statement that displays a thread in a mailer view.

When I was using routing-filter I had the link_to statement as below where I set @host in my mailer depending on the environment.

<%= link_to "#{t :view_thread}", micropost_url(@item), host: "#{@host}" %>

When I uninstalled routing-filter I started getting errors because of a missing locale when the attempt is made to send the email. It crashes and sends the application back to the landing page. The gem took care of this.

I have been searching for about an hour trying to find the correct syntax for this but I'm not finding any examples that include both the host and locale parameters. I have tried several guesses but I get syntax errors.

Any help would be appreciated. I will keep searching and trying.

Was it helpful?

Solution

Here is the solution I came up with. I was not sure where the locale clause should go related to the host clause. I decided to try the statement below and it worked.

<%= link_to "#{t :view_thread}", micropost_url(@item, locale: I18n.locale.to_s), host: "#{@host}" %>

OTHER TIPS

Updated solution for Rails 6 (and probably 5).

First, make sure you followed Rails guides on localization, so it's all set up

Then, add this to your ApplicationMailer:

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

This will use your selected locale for links generation, so you don't have to pass locale: @locale every time.

And then, set current locale in your mailers with the following block.

    I18n.with_locale(@locale) do
      mail(to:      @email,
           subject: I18n.t("mailers.my_mailer.subject"))
    end

The last piece of advice - don't forget to fallback with your @locale var, so it's smth along these lines: @locale = @user.locale || I18n.default_locale

Update:

Or you can simply monkeypatch mail method, but make sure you know what you're doing.

  def mail(**)
    I18n.with_locale(@locale || I18n.default_locale) { super }
  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top