2013-04-24 82 views
0

我有一個類鏈接。這個類有這些屬性格式的自定義驗證

  1. Twitter的
  2. Facebook的
  3. Pinterest的
  4. Quora的

我想,當用戶插入一個鏈接到它啓動一個文本框寫一個證明,確認可確保與http或https。

驗證工作,但我有一個問題,當用戶根本沒有插入鏈接。它仍然嘗試對空屬性運行驗證並引發錯誤。下面的代碼是我嘗試檢查一個空屬性。

這裏是我的驗證:

 class Links < ActiveRecord::Base 
    attr_accessible :facebook, :twitter, :quora, :pinterest 

    validate :formatted_link 

    def formatted_link 
     links = %w(facebook twitter pinterest quora) 
     if links.any? {|link| self[link].nil?} 
     #Don't want it to do any validation if column is nil. 
     #Would like to drop column if user doesn't add a link. 
     else 
      validates_format_of links, :with => URI::regexp(%w(http https)) 
      errors.add(:base, "Your link must start with http or https.") 
     end 
    end 

原因:

如果用戶只是提交「www.twitter.com/username」的網址,以獲取的追加到我的網站的網址「mydomain.com/page/ www.twitter.com/username。不知道爲什麼發生這種情況。如果有別的東西,我可以做些什麼來防止這種情況還是我丟失的東西,請讓我知道。

感謝。

回答

0

我認爲你正在試圖做的conditional validation以一種迂迴的方式。既然你真的只是想讓空白,你可以這樣做:

class Link < ActiveRecord::Base 
    Networks = [:facebook, :twitter, :quora, :pinterest] 
    attr_accessible *Networks 

    validates_format_of *Networks, :with => URI::regexp(%w(http https)), :allow_blank => true 
end 
+0

謝謝davogones,allow_blank工作。不能投票答案B/C我沒有足夠的代表點。 – Zach 2013-04-25 15:59:28

1

我認爲您需要在將links轉換爲符號之前將其轉換爲validates_format_of,但由於它似乎適用於您,因此我可能是錯的,或者上面的示例代碼可能會遺漏該細節。

無論哪種方式,你可以在空白跳過驗證有:

validates_format_of :foo, with: some_format, allow_blank: true 
+0

謝謝吉姆。添加了:allow_blank。 – Zach 2013-04-25 15:42:07