所以我想在我的网站上有网址,例如http://foobar.com/hadees http://foobar.com/hadees这会进入某人的个人资料。但是,在注册用户名时,如何确保他们不会选择与我现有的路由冲突的内容?
我猜我需要获取现有路线的列表,但我不知道该怎么做。
简短的谷歌搜索给了我:
http://henrik.nyh.se/2008/10/validating-slugs-against-existing-routes-in-rails http://henrik.nyh.se/2008/10/validating-slugs-against-existing-routes-in-rails
在 Rails 3 中,该方法已移至 Rails.application.routes.recognize_path
所以我总结一下:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)