enriclluelles/route_translator

Optional route params not included in translated URL

seanabrahams opened this issue · 2 comments

Steps to reproduce*

rails new optional

config/initializers/i18n.rb

I18n.available_locales = %i[en es]
I18n.default_locale = :en

routes.rb

Rails.application.routes.draw do
  localized do
    get "posts(/page/:page(/items/:items))", controller: :posts, action: :index, as: :posts
    root "posts#index"
  end
end

app/controllers/posts_controller.rb

class PostsController < ApplicationController
end

app/views/posts/index.html.erb - taken from https://github.com/enriclluelles/route_translator/wiki/Generating-translated-URLs

<% I18n.available_locales.each do |locale| %>
  <%= link_to locale, url_for(locale: locale.to_s, only_path: true), rel: 'alternate', hreflang: locale.to_s %>
<% end %>

Expected behavior*

If you load /posts/page/2 the link to the es translated URL should be /es/posts/page/2

Actual behavior*

If you load /posts/page/2 the link to the es translated URL will be /es/posts

System configuration*

Rails version: Rails 7.0.3.1
Ruby version: ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [aarch64-linux]
Route Translator version: route_translator (12.1.0)

I18n configuration*

I18n.available_locales = %i[en es]
I18n.default_locale = :en

Route Translator initializier

Did not create one.

Source code of routes.rb*

Source of: config/routes.rb

Rails.application.routes.draw do
  localized do
    get "posts(/page/:page(/items/:items))", controller: :posts, action: :index, as: :posts
    root "posts#index"
  end
end

Output of rails routes*

Result of bundle exec rails routes:

posts_es GET /es/posts(/page/:page(/items/:items))(.:format)  posts#index {:locale=>"es"}
posts_en GET /posts(/page/:page(/items/:items))(.:format)  posts#index {:locale=>"en"}
root_es  GET /es  posts#index {:locale=>"es"}
root_en  GET /  posts#index {:locale=>"en"}

Hi!

Thanks for being part of the Route Translator community and apologies for the late reply

I think this issue is not related to Route Translator but it depends on how url_for works for routes with optional parameters

Example on a basic Rails application without Route Translator:

# routes.rb
Rails.application.routes.draw do
  get "posts(/page/:page(/items/:items))", controller: :posts, action: :index, as: :posts
end
<!-- index.html.erb -->
<%= url_for %>

Url: http://localhost:3000/posts/page/2

Output: /posts

I will clarify in the Wiki that url_for works for basic use cases and that optional route parameters are not taken into account

It is possible to force the params by using

<%= url_for(**params.permit!) # DON'T %>

but I would not do that. Probably this use case requires a custom url generation technique

Hope it helps

Closing here, but feel free to comment

Thank you for the response, updating the Wiki page, and for keeping this gem in good shape. Appreciate it.