How to localized URL's in Ruby On Rails

207 Views Asked by At

For now my routes.rb looks like this:

  scope '(:locale)', locale: /en/ do  
    get I18n.t('routes.pages.about'), to: 'pages#about', as: 'about'
    get 'media', to: 'pages#media', as: 'media'
    get 'career', to: 'pages#career', as: 'career'
    get 'how_it_works', to: 'pages#works', as: 'works'
    get 'privacy_policy', to: 'pages#privacy_policy', as: 'privacy_policy'
    get 'contact', to: 'pages#contact', as: 'contact'
    get 'publications', to: 'pages#publications', as: 'publications'
    get 'our_team', to: 'pages#our_team', as: 'our_team'
    get 'partners', to: 'pages#partners', as: 'partners'
    get 'blog', to: 'posts#index', as: 'blog'
    get 'map', to: 'pages#map', as: 'map'
    get 'association', to: 'pages#association', as: 'association'
    get 'questions_and_answers', to: 'pages#questions_and_answers', as: 'questions_and_answers'
    resources :posts, only: [:show]
    get '/users/:uuid', to: 'users#public_profile'
    post 'partners/:partner', to: 'pages#partners_partial', as: 'partners_partial'
  end

I created routes.yml file in 'config/locales'

pl:
  routes:
    pages:
      about: "o-nas"
      media: ""
      career: ""
      how_it_works: ""
      privacy_policy: ""
      contact: ""
      publications: ""
      our_team: ""
      partners: ""
      blog: ""
      map: ""
      association: ""
      question_and_answers: ""
en:
  routes:
    pages:
      about: "about"
      media: ""
      career: ""
      how_it_works: ""
      privacy_policy: ""
      contact: ""
      publications: ""
      our_team: ""
      partners: ""
      blog: ""
      map: ""
      association: ""
      question_and_answers: ""

My application_controller.rb:

  def default_url_options
    { locale: I18n.locale == I18n.default_locale ? nil : I18n.locale }
  end

  private

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

My switch language buttons:

-if I18n.locale == :pl
  = link_to "/en#{request.fullpath}", { :lang=>'en'} do
    = image_tag'/england-flag.ico', size: '25x25', class: 'rounded-xl shadow', alt: 'Switch to English language'
-else
  = link_to "/#{request.fullpath.split('/en/')[1]}", { :lang=>'pl'} do
    = image_tag'/poland-flag.ico', size: '25x25', class: 'rounded-xl shadow', alt: 'Przełącz na język Polski'

As you can see, I tried to localized URL for about page, but... sometimes it shows me 'o-nas' and sometimes it shows me 'about' (even though I haven't changed language). I know there are gems like 'friendly_id-globalize', I even try this one, but it was not what i was looking for. Is that even possible to dynamically change routes?

1

There are 1 best solutions below

0
Grzegorz Ciężkowski On

I think You should change your route file line to

scope '(:locale)', locale: /en|pl/ do  

You missed polish language.