Rails — Params with “dot” (e.g. /google.com)

前端 未结 4 780
情歌与酒
情歌与酒 2020-12-09 04:02

How to force Rails to consider a param with a dot in the value like google.com (e.g. /some_action/google.com) a single param and not \"id\" =

相关标签:
4条回答
  • 2020-12-09 04:09

    We had similar case when we removed some part of an api path. Basically we went from /api/app/v1/* to /api/v1/*

    We put this in our routes

    match '/api/app/v1/*path', to: redirect(path: '/api/v1/%{path}'), via: :all
    

    This was all fine except for some routes that ended with path params including dots. E.g. /api/v1/foo/00.00.100 where .100 got parsed into format and the remaining param only had the value 00.00

    We guarded this with some constraint on the params.

    put '/api/app/v1/foo/:version', 
        constraints: { version: /([0-9]+)\.([0-9]+)\.([0-9]+)/ },
        to: redirect('/api/v1/foo/%{version}')
    

    Edit: we use rails 5

    0 讨论(0)
  • 2020-12-09 04:14

    In Rails 4 I used:

    get 'operation/:p1/:p2', to: 'operation#get', constraints: { p1: /[^\/]+/, p2: /[^\/]+/ }
    

    it allows any character in both params (other than '/')

    0 讨论(0)
  • 2020-12-09 04:14

    And when used with the resources notation, it can be done like this:

    resources :post, 
                   only: [ :create, :index, :destroy ], 
                   constraints: { id: /[0-z\.]+/ }
    

    Tested in Rails 4.1

    0 讨论(0)
  • 2020-12-09 04:22

    By default, dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. However, you can add some regex requirements to the route parameters. Here, you want to allow the dots in the parameters.

    match 'some_action/:id' => 'controller#action', :constraints  => { :id => /[0-z\.]+/ }
    

    And in rails 2.3:

    map.connect 'some_action/:id', :controller => 'controller', :action => 'action',  :requirements => { :id => /[0-z\.]+/ } 
    

    Relevent rails guides section

    0 讨论(0)
提交回复
热议问题