had*_*ees 5 routing ruby-on-rails-3
所以我想在我的网站上设置网址,例如http://foobar.com/hadees,这些网址会转到某个人的个人资料中.但是,在注册用户名时,如何确保他们不会选择与我现有路由冲突的内容?
我猜我需要获得现有路线的清单,但我不知道该怎么办.
Tho*_*ory 10
一个简短的谷歌搜索给了我:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
402 次 |
| 最近记录: |