本文介绍了如何确定用户名不会与现有路由冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我想在我的网站上使用这样的网址,转到某人的个人资料。但是,在注册用户名时,如何确定它们不会选择与现有路由冲突的内容?
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.
推荐答案
一个简短的Google搜索结果就是:
A short google search gives me that:
在rails 3中方法已移至Rails.application.routes.recognize_path
In rails 3 the method has moved to 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
这篇关于如何确定用户名不会与现有路由冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!