How can you make sure the username does not conflict with an existing route?

So, I would like to have URLs on my site, like http://foobar.com/hadees , which gets into someone's profile. However, when registering usernames, how can I make sure that they don’t choose something that contradicts my existing routes?

I guess I need to get a list of existing routes, but I'm not sure how to do this.

+4
source share
2 answers

A short google search gives me the following:

http://henrik.nyh.se/2008/10/validating-slugs-against-existing-routes-in-rails

On rails 3, the method has moved to Rails.application.routes.recognize_path

So, I summarize:

class User < ActiveRecord::Base validates_format_of :name, :with => /\A[\w-]+\Z/ validates_uniqueness_of :name validate :name_is_not_a_route protected def name_is_not_a_route path = Rails.application.routes.recognize_path("/#{name}", :method => :get) rescue nil errors.add(:name, "conflicts with existing path (/#{name})") if path && !path[:username] end end 
+10
source
Good question. Through a little intervention, I discovered that you can get routes in your application through:
 Rails.application.routes.routes.collect{|r| r.path} 
+2
source

Source: https://habr.com/ru/post/1403970/


All Articles