Rails REST routing: dots in the resource item ID

sandrew picture sandrew · Mar 7, 2011 · Viewed 10.9k times · Source

I have following in my routes.rb:

resources :users, :except => [:new, :create] do
    get 'friends', :as => :friends, :on => :member, :to => "users#friends"
end

and following in my user.rb:

def to_param
  self.login
end

And when, for example, user with dots in login (for example 'any.thing') comes from facebook, rails gives routing error (no route found, I suppose that's because it recognises anything after dot as a format or because of route constraints). How can I come over this error?

Answer

senotrusov picture senotrusov · Sep 29, 2011

The following constrain definition permit the dot in id as well as any character except slash.

Supported formats must be explicitly defined (here .html and .json) to not to be taken by id.

resources :foobars,
  :constraints => { :id => /[^\/]+(?=\.html\z|\.json\z)|[^\/]+/ }

That constrain definition is worked with Rails 3.1

For earlier Rails versions you may need to backport look-ahead support in regin gem (it is vendored in rack-mount gem)