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

こ雲淡風輕ζ 提交于 2019-12-05 09:53:07
Thomas Guillory

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

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