2012-03-28 64 views

回答

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 
2

好問題。經過稍微修改一下,我發現,你可以通過在你的應用程序的路徑:

Rails.application.routes.routes.collect{|r| r.path}