I'm aware this has probably been asked before but for some reason I can't get it to work with button_tags. If I modify the URL manually it works perfectly.
routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
scope '(:locale)' do
root 'welcome#index'
post 'set_locale', controller: 'application'
get 'who_we_are/index', to: 'who_we_are#index', as: 'who-we-are'
resources :properties
end
end
application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
application.html.erb
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<%= form_tag('/set_locale') do -%>
<%= button_tag '🇺🇸'.html_safe, name: 'locale', value: 'en', type: 'submit', class: 'btn' %>
<%= button_tag '🇪🇸'.html_safe, name: 'locale', value: 'es', type: 'submit', class: 'btn' %>
<% end %>
</li>
</ul>
When clicking on any of the buttons (code is an emoji flag FYI), nothing happens. This is on the log:
Started POST "/set_locale" for ::1 at 2022-09-21 00:19:25 -0600
Processing by ApplicationController#set_locale as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "locale"=>"en"}
No template found for ApplicationController#set_locale, rendering head :no_content
Completed 204 No Content in 3ms (ActiveRecord: 0.0ms | Allocations: 504)
The no_content warning leaded me to think that I had to add this after the I18n.locale = params[:locale] || I18n.default_locale line:
respond_to do |format|
format.html { redirect_back(locale: params[:locale], fallback_location: root_path) }
end
Doing that sends the page into infinite redirects. Ideally, I'd want that the buttons redirect to the same page but with different locale (my URL format is localhost:3000/:locale/the_page), but if it's not possible, I'll be happy with root_path.