Search code examples
ruby-on-railsroutesrails-routing

Creating a prefix route in rails


I want to create URLs of the form /suffix-<slug> with rails but I can't see how to map that on the routes.rb, how can I do that?


Solution

  • Well, one way to achieve that is to consider the prefix as part of the id and then handle removing it in the controller:

    routes.js

    # Only for one place
    post '/:id' , to: 'books#create', id: /prefix-.*/
    
    # Same format in multiple places
    constraints(id: /prefix-.*/) do
      post '/:id' , to: 'books#create'
      ...
      # Works with resources as well
      resources 'objects'
    end 
    

    Controller

    def create
      params[:id].slice! "prefix-"
      ...
    end