Rails — Params with "dot" (e.g. /google.com)
Asked Answered
P

4

26

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" => "google", "format"=> "com"?

The parameter value should be "id" => "google.com"

Preemie answered 1/6, 2010 at 18:23 Comment(0)
L
39

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

Leontine answered 1/6, 2010 at 18:32 Comment(1)
There's some problems with that regex. how about /[\w.]+/ ?Longe
R
6

In Rails 4 I used:

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

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

Reprise answered 4/9, 2014 at 18:33 Comment(0)
W
4

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

Whish answered 5/10, 2015 at 18:53 Comment(0)
A
1

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

Allotment answered 8/2, 2017 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.