2010-01-24 40 views

回答

2

我會建議您在將它們存儲在數據庫中甚至驗證之前,對URL進行標準化(添加/剝離尾部斜槓等,請參閱http://en.wikipedia.org/wiki/URL_normalization)。

validates_uniqueness_of :link, :case_sensitive => false 
before_validation :normalize_urls 

def normalize_urls 
    self.link.strip! 
    self.link.gsub!(/\/$/,'') 
end 

這不是你問的很什麼,但如果你不存儲標準化的網址,您要查詢驗證過程中以及對所有可能的變化DB和可以迅速得到昂貴。

1

您可以隨時執行自定義驗證程序(例如,使用validate方法)。

它可能是這個樣子:

class MyModel < ActiveRecord::Base 
    validate :link_is_unique 

    def link_is_unique 
    #Clean up the current link (removing trailing slashes, etc) 
    link_to_validate = self.link.strip.gsub(/\/$/,'') 

    # Get the current count of objects having this link 
    count = MyModel.count(:conditions => ['link = ?', link_to_validate]) 

    # Add an error to the model if the count is not zero 
    errors.add_to_base("Link must be unique") unless count == 0 
    end 
end 

然後,您可以添加其他邏輯,以清理鏈接(即檢查HTTP:// WWW等)