0
我目前正面臨着使用自定義的驗證on Rails的4.第一個問題2個問題,我怎樣才能使下面的代碼更通用,高效的(如果可能的話)?軌道4驗證是否NUM1> NUM2> NUM3
validates :p1, presence: true, numericality: { only_integer: false }
validate :p1_is_greater_than_p2_and_p3
validate :p2_between_p1_and_p3
validate :p3_is_less_than_p2_and_p1
def p1_is_greater_than_p2_and_p3
if self.p1.present?
errors.add(:p1, 'p1 must be greater than everything') unless
(self.p1 > self.p2) && (self.p1 > self.p3)
end
true
end
def p2_between_p1_and_p3
if self.p3.present?
errors.add(:p2, 'p2 bewteen p1 and p3') unless
self.p2.between?(self.p1, self.p3)
end
true
end
def p3_is_less_than_p2_and_p1
if self.p2.present? and self.p3.present?
errors.add(:p3, 'p3 must be inferior to eveything') unless
(self.p2 > self.p3) && (self.p1 > self.p3)
end
true
end
它真的臃腫骯髒,不是嗎?
第二個問題上errors.add
,我可以通過一個符號和錯誤消息。但是,如果我不傳遞任何消息,我怎樣才能爲我的語言環境定義自定義yml密鑰?如:
en:
activerecord:
errors:
models:
prices:
attributes:
custom_key_message_here: 'p1 must be greater than everything'
我想保持區域設置和模型之間的這種關注的分離。但是,如果我不傳遞任何消息,它會顯示我is invalid
。我想要更多的東西爆炸。
感謝您的幫助。
完美。在論壇上,我看到這是不可能的,因爲'greater_than'只接受整數,所以我甚至沒有使用屬性自己嘗試。奇蹟般有效。謝謝 – lkartono