Search code examples
ruby-on-railscontactsmail-form

How can I change the language of a posted view?


I have a view that is called using the method post and not get. But when I want to change the language of the view in rails using I18n and change_locale_path(:es). I have routing problems because there is no route that matches [Get]"/Contacts" and localhost:3000/contacts is called with post.

My apllication.html.erb is:

<li><%= link_to (t ('layouts.language1')) , change_locale_path(:es) %></li>

My routes file is:

resources :contacts, only: [:new,:create]
get 'gmm/home' 
get 'gmm/about'
get 'gmm/services'
get 'gmm/contact'
get '/change_locale/:locale', to: 'settings#change_locale', as: :change_locale

I also tries adding this to the routes file.

match ':controller/:action' ,via: [:get,:post]

Solution

  • You can just add method: :post to send request as post.

    <li><%= link_to (t ('layouts.language1')) , change_locale_path(:es), method: :post %></li>
    

    Secondly: if you are on /contacts page and want to change locale. You can send change locale request using ajax also.

    For sending request using ajax:

    <li><%= link_to (t ('layouts.language1')) , change_locale_path(:es), method: :post, remote: true %></li>