我有一個類鏈接。這個類有這些屬性格式的自定義驗證
- Twitter的
- Facebook的
- Pinterest的
- 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。不知道爲什麼發生這種情況。如果有別的東西,我可以做些什麼來防止這種情況還是我丟失的東西,請讓我知道。
感謝。
謝謝davogones,allow_blank工作。不能投票答案B/C我沒有足夠的代表點。 – Zach 2013-04-25 15:59:28