How can you make sure a username won't conflict with an existing route?

大憨熊 提交于 2019-12-07 05:22:17

问题


So I'd like to have urls on my site like http://foobar.com/hadees that goes to someone's profile. However when registering usernames how do I make sure they don't pick something that will conflict with my existing routes?

I'm guessing I need to get a list of the existing routes but I'm not sure how to do it.


回答1:


A short google search gives me that:

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

In 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



回答2:


Good question. Through a little tinkering, I found that you can get the routes in your app via:

Rails.application.routes.routes.collect{|r| r.path}


来源:https://stackoverflow.com/questions/9913064/how-can-you-make-sure-a-username-wont-conflict-with-an-existing-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!