所以我想在我的網站上找到像http://foobar.com/hadees這樣的網址,這些網址會轉到某人的個人資料。但是,在註冊用戶名時,我如何確保他們不會選擇與我現有路線衝突的內容?如何確保用戶名不會與現有路線衝突?
我猜我需要得到現有路線的列表,但我不知道如何去做。
所以我想在我的網站上找到像http://foobar.com/hadees這樣的網址,這些網址會轉到某人的個人資料。但是,在註冊用戶名時,我如何確保他們不會選擇與我現有路線衝突的內容?如何確保用戶名不會與現有路線衝突?
我猜我需要得到現有路線的列表,但我不知道如何去做。
短谷歌搜索給我說:
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
好問題。經過稍微修改一下,我發現,你可以通過在你的應用程序的路徑:
Rails.application.routes.routes.collect{|r| r.path}