Rails mountable engine under a dynamic scope

2019-02-16 01:36发布

问题:

say that I have these routes:

scope '(:locale)', :locale => /en|de/ do
  mount Users::Engine => "users", as: 'users_engine'  
end

and in engine's view:

<%= link_to 'new user', action: :new, controller: :users, locale: :de %>

I get

/en/users/users/new?locale=de 

instead of

/de/users/users/new

I have already included in application controller:

def set_locale
  if params.include?('locale')
    I18n.locale = params[:locale]
    Rails.application.routes.default_url_options[:locale] = I18n.locale
  end
end

and it works fine in the main app

I have found a way to get the right url by

Users::Engine.routes.url_for controller: 'users/users', action: :new, only_path: true, locale: :de

but I think that there should be a better way and what if I was making a change-locale link in the layout ?

<%= link_to locale: :de %>

I cannot know which exact engine this could be

Thanks vm.

回答1:

I think I have found a solution for that...

Just use the url_options-method in your application_controller.rb-File (see link below)

See: https://stackoverflow.com/a/18299975/603126

Hope it helps!

Regards

Philipp