Flip
Flip

Reputation: 6771

Constraints not working when using block syntax in Rails

I tried to add constraints to a group of scoped routes like so:

constraints locale: 'de' do
  scope 'magazin' do
    get '', to: 'magazine#index', as: 'magazine'
    # more routes
  end
end

It doesn't make use of the restriction. Whereas putting the restriction to a single route works as expected.

get '', to: 'magazine#index', as: 'magazine', constraints: { locale: 'de' }

I tried to use the constraints block in different positions, inside and outside the scope block. Without any change in the result.

The Rails Guide for Routing has this example which I pretty much copied:

namespace :admin do
  constraints subdomain: 'admin' do
    resources :photos
  end
end

Any ideas what's wrong with the code?

Upvotes: 1

Views: 738

Answers (1)

basiszwo
basiszwo

Reputation: 620

Without having the whole routes.rb file it is hard to say why it doesn't work as expected.

Is it possible you have some kind of scope defined for locale??

Imagine sth like

scope '/:locale', locale: /de|en/ do
  # lots of routes so you are not aware of the scope
  constraints locale: "de" do
    scope 'magazin' do
      get '', to: 'magazine#index', as: 'magazine'
    end
  end
end

With this your are actually setting a constraint to locale to be either de or en. The constraint from the scope has precedence over the constraints block.

While this is not clear from the rails guide I found a merge request that proves my argumentation.

Upvotes: 2

Related Questions