如何驗證一個字段或另一個字段的存在,但不是兩個字段或至少一個字段?驗證是否存在一個或另一個字段(XOR)
64
A
回答
111
如果條件語句添加到numericality驗證,像這樣你的代碼將工作:
class Transaction < ActiveRecord::Base
validates_presence_of :date
validates_presence_of :name
validates_numericality_of :charge, allow_nil: true
validates_numericality_of :payment, allow_nil: true
validate :charge_xor_payment
private
def charge_xor_payment
unless charge.blank?^payment.blank?
errors.add(:base, "Specify a charge or a payment, not both")
end
end
end
9
鋼軌3.
class Transaction < ActiveRecord::Base
validates_presence_of :date
validates_presence_of :name
validates_numericality_of :charge, :unless => proc{|obj| obj.charge.blank?}
validates_numericality_of :payment, :unless => proc{|obj| obj.payment.blank?}
validate :charge_xor_payment
private
def charge_xor_payment
if !(charge.blank?^payment.blank?)
errors[:base] << "Specify a charge or a payment, not both"
end
end
end
2
validate :father_or_mother
#Father姓或母姓例強制
def father_or_mother
if father_last_name == "Last Name" or father_last_name.blank?
errors.add(:father_last_name, "cant blank")
errors.add(:mother_last_name, "cant blank")
end
end
試試上面的簡單例子。
7
class Transaction < ActiveRecord::Base
validates_presence_of :date
validates_presence_of :name
validates_numericality_of :charge, allow_nil: true
validates_numericality_of :payment, allow_nil: true
validate :charge_xor_payment
private
def charge_xor_payment
if [charge, payment].compact.count != 1
errors.add(:base, "Specify a charge or a payment, not both")
end
end
end
,你甚至可以用3個或多個值做到這一點:
if [month_day, week_day, hour].compact.count != 1
31
我認爲這是Rails的更地道3+:
如:用於驗證的user_name
或email
一個是目前:
validates :user_name, presence: true, unless: ->(user){user.email.present?}
validates :email, presence: true, unless: ->(user){user.user_name.present?}
+18
這不處理「不是兩個」標準 – 2014-06-03 01:22:27
0
我把我的答案在下面這個問題。在這個例子中:description
和:keywords
是字段,其中這一個不能爲空:
validate :some_was_present
belongs_to :seo_customable, polymorphic: true
def some_was_present
desc = description.blank?
errors.add(desc ? :description : :keywords, t('errors.messages.blank')) if desc && keywords.blank?
end
這就是所謂的完美的答案。謝謝@Semanticart – 2016-04-29 13:00:24
功能很好。但是,我無法獲取表單頁面上顯示的錯誤。除非我在我的_form.slim上做'= @ invoice.errors [:base] [0]'之類的東西。有什麼建議麼? – 2016-05-18 17:36:36