How to prevent profile URLs from matching with other routes

If I wanted user urls to look like

http://site.com/foobar 

instead

http://site.com/users/foobar

foobarwill be the alias of the user from the column nicknamein the user model. How can I prevent users from registering top-level routes? How to contact, oh, logout, etc.?

I may have a table of reserved names. Therefore, when a user registers an alias, he will check this table. But is there a more convenient approach?

+3
source share
1 answer
if(Rails.application.routes.recognize_path('nickname') rescue nil)
  # forbid using desired nickname
else
  # nickname can be used -- no collisions with existing paths
end

UPD:

If any path seems to be recognized recognize_path, then you have something like:

get ':nick' => 'user#show'

routes.rb, , . , . :

# in routes.rb
class NickMustExistConstraint
    def self.matches?(req)
        req.original_url =~ %r[//.*?/(.*)] # finds jdoe in http://site.com/jdoe. You have to look at this regexp, but you got the idea.
        User.find_by_nick $1
    end
end
get ':nick' => 'users#show', constraints: NickMustExistConstraint

, , jdoe, /jdoe. rroe, /rroe, .

, , :

# in User.rb
def to_param
  nick
end
# in routing.rb
resources :users, path: 'u'

/u/jdoe ( REST).

, User.find_by_nick! params[:id] (, params[:id], , , ).

+1

All Articles