3

Is there any way I can add a validation to the user model such that usernames that are the same as already defined routes are rejected?

For instance:

get 'search'
get :username => "users#show", :as => :user

If the user enters "search" as the username it would reject it because that already exists as a rails route.

The possible other approach is to create an explicit blacklist, but obviously that requires more maintenance as new routes are added.

Edit

Adapted answer into working solution:

validate :username_blacklist

private
@@username_blacklist = nil

# checks if the username is on a blacklist
def username_blacklist
  unless @@username_blacklist
    @@username_blacklist = Set.new [ "badword", "naughtybadfun"]
    Rails.application.routes.routes.each do |r|
      reserved_word = File.dirname(r.path).split('/')[1]
      @@username_blacklist << reserved_word if reserved_word
    end
  end

  errors.add(:username, "is restricted") if @@username_blacklist.include?(username)
end
2
  • I don't recommend you to use this approach :)
    – fl00r
    May 12, 2011 at 22:40
  • @fl00r can you elaborate on why you don't recommend this approach? May 10, 2012 at 22:29

3 Answers 3

1

In your validation you could loop through all the defined routes and check them against the desired username.

This helps you to get the defined paths:

Rails.application.routes.routes.each {|r| p r.path.to_s}
0
1

the simpliest way for validation is passing username as a url, and if there is 404 PageNotFound response so username can be used :)

1
  • A step up from that would be to write all the routes to file every time code is redeployed & just check against the file.
    – klochner
    May 12, 2011 at 22:39
0

Well you actually got the desired behaviour already, because the first matched route is used. So a request to /search would never reach the 2nd route.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.