2015-11-19 35 views
0

我有一些驗證規則模型:Ruby on Rails的4型號有條件驗證

class Order < ActiveRecord::Base 

    validates :zip_code, presence: true, length: {is: 5}, numericality: {only_integer: true, :greater_than => 0} 
end 

當ZIP_CODE是空白的我並不需要執行其他ZIP_CODE驗證(它是多餘的,所有其他的驗證消息在用戶頁面上看起來很奇怪,如果zip_code爲空)

我該如何實現這個邏輯?我需要驗證length, is_integer and greater_than only if zip_code is not blank?,我需要用戶頁面上只顯示zip_code can't be blank消息

回答

2

你可以做這樣的事情

validates :zip_code, presence: true 
validates :zip_code, length: {is: 5}, numericality: {only_integer: true, :greater_than => 0}, :if => :zip_code? 

希望它能幫助!

+0

謝謝!它有助於 –

+0

完成,我不得不等待3分鐘將其標記爲答案。多謝 –