Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

like image 973
There Are Four Lights Avatar asked Jun 01 '10 18:06

There Are Four Lights


3 Answers

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

like image 122
Damien MATHIEU Avatar answered Nov 05 '22 07:11

Damien MATHIEU


In Rails 4 I used:

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

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

like image 5
AlejandroVD Avatar answered Nov 05 '22 08:11

AlejandroVD


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

like image 3
Alf Steed Avatar answered Nov 05 '22 06:11

Alf Steed