Home Rails: Catch a request in a scope when the request doesn't match anything in the scope
Reply: 2

Rails: Catch a request in a scope when the request doesn't match anything in the scope

David B.
1#
David B. Published in 2017-12-07 13:35:47Z

Let's take the following router :

Rails.application.routes.draw do
  scope ":locale", locale: /en|nl/ do
    get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
  end

  root to: "pages#simple_action"
  get "/:slug", to: "pages#simple_action", constraints: { slug: /.*/ }
end

If the request specifies a locale, the scope catches it and forwards it to pages#prefixed_action. If not the request is forwarded topages#simple_action.

My issue is that if I enter localhost:3000/en in the browser, it won't be catched by the scope. How can I arrange that ?

Edit1: I'd like the request to be routed to "pages#prefixed_action"

Edit2: added a root declaration in the code sample

maicher
2#
maicher Reply to 2017-12-07 14:32:47Z

One of the possibilities is to specify root inside the scope:

scope ":locale", locale: /en|nl/ do
  root 'pages#prefixed_action'
  get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
end
J.D.
3#
J.D. Reply to 2017-12-07 14:59:01Z

Maybe simply like this:

get '/:locale', to: "pages#prefixed_action", constraints: { locale: /(en|nl)/ }
get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ }    

If your goal is to send to pages#prefixed_action with paths /en and /nl and all other to pages#simple_action. If so, put

get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ } 

As a last route in your routes

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305157 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO