ruby-on-railsrelative-pathrails-routingtrailing-slash

Enforce trailing slash in Rails Routing


Adding a trailing slash in your links is easy enough with {:trailing_slash => true}, but this doesn't account for if a user types in a non-slashed url. Is there a way to enforce trailing slashes via redirects in the router?

get "/:controller/:id" => redirect{|params| "/#{params[:controller]}/#{params[:id]}/" }

The above leads to a circular loop.

Why?

a relative link of "./subclass" on

/parent/1

is much different than

/parent/1/

Solution

  • in the config/application.rb file, add

    config.action_controller.default_url_options = { :trailing_slash => true }
    

    in the Application class