2011-03-16 92 views
2

我有一個Rails 3.0網絡應用程序,允許用戶創建自己的路徑到應用程序。控制器中的測試路由

example : www.my_app.com/user_company_name 

因此,我在用戶數據庫字段中存儲自定義路徑。用戶可以通過輸入更改路徑。

我在模型

validates_presence_of :custom_page 
validates_format_of :custom_page, :with => /^([a-z]|[0-9]|\-|_)+$/, :message => "Only letter (small caps), number, underscore and - are authorized" 
validates_length_of :custom_page, :minimum => 3 
validates_uniqueness_of :custom_page, :case_sensitive => false 

加入這個驗證,但我不知道我怎麼能確認網址是否是不衝突的,在我的路由另一條路線。

舉例來說,在我的route.rb我有

resources :user 

驗證需要使用www.my_app.com/user到不允許,我可怎麼辦呢?

感謝,文森特

回答

0

在你的路線,你的公司名稱相匹配的變量

match 'some_path/:company_name.format' 

那麼你可以做使用COMPANY_NAME這Rails會爲你查找。

驗證custom_page變量的唯一性應該足以確保沒有重疊。 (請注意,驗證唯一性並不會擴展 - 如果這樣做會很大,您還需要db約束),只要用戶只能指定一個字段即可。

如果你讓用戶指定

'some_path/:custom_path_1/:custom_path_2.format' 

,那麼你必須在這兩個領域來驗證,而現在它變得凌亂。希望你沒有那樣做。

0

你可以嘗試自定義驗證來清除「用戶」

validate :custom_page_cant_be_user 

def custom_page_cant_be_user 
    errors.add(:custom_page, "can't be `user`") if self.custom_page =~ /^user$/i 

end 

假設:custom_page就會出現,一個基本的[a-z],如果:custom_page/user你需要更新正則表達式一點。