我有這個 before_save 功能:
def set_birth_date
return unless pesel_changed?
day = pesel[4..5]
case pesel[2..3].to_i
when 0..19
month = pesel[2..3]
year = pesel[0..1].prepend('19')
when 20..39
month = (pesel[2..3].to_i - 20).to_s
year = pesel[0..1].prepend('20')
when 40..59
month = (pesel[2..3].to_i - 40).to_s
year = pesel[0..1].prepend('21')
when 60..79
month = (pesel[2..3].to_i - 60).to_s
year = pesel[0..1].prepend('22')
end
birth_date = Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y')
if birth_date.valid?
self.birth_date = birth_date
else
errors.add(:pesel, I18n.t('activerecord.errors.models.profile.attributes.pesel.invalid'))
end
end
(小解釋:最后一個 if 條件還沒有包含在函式中。我想要做的就是保存birth_date 如果有效,但如果它無效,我想添加錯誤。)但有時它會給我這樣的錯誤:
`strptime': invalid date or strptime format - `12/14/2022' `%d/%m/%Y' (ArgumentError)
如何檢查 Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y') 是否有效?“有效的?” 和“有效日期?” 不作業。幾個月來我可以做這樣的事情
if month / 12 > 0
<Handling error>
else
<update>
end
但是幾天... 這不會那么容易。有任何想法嗎?
編輯: pesel 是一個字串。此功能從比塞爾號中提取出生日期。Pesel 號碼是 11 位數字,例如:
50112014574
50 - year of birth
11 - month of birth
20 - day of birth
14574 - Control number
Those "magic numbers' defines which year someone was born
If someone was born in 19XX, then month number is 1-12.
If someone was born in 20XX, then month number is 21-32 (month number 20. Example pesel number: '50312014574', which means this person was born 20th November 2050
If someone was born 21XX, then month number is 41-52 (month nubmer 40) Example pesel number: '50512014574', which means this person was born 20th November 2150 etc.
我正在處理現有資料庫,我不能只驗證 pesel 號
uj5u.com熱心網友回復:
如果您不能pesel首先驗證資料庫中的數字,那么我只會捕獲錯誤并在一個rescue塊中處理它。
為此改變
birth_date = Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y')
if birth_date.valid?
self.birth_date = birth_date
else
errors.add(:pesel, I18n.t('activerecord.errors.models.profile.attributes.pesel.invalid'))
end
到
begin
birth_date = Time.strptime("#{day}/#{month}/#{year}", '%d/%m/%Y')
self.birth_date = birth_date
rescue ArgumentError => e
errors.add(:pesel, I18n.t('activerecord.errors.models.profile.attributes.pesel.invalid'))
end
uj5u.com熱心網友回復:
有了年份和月份后,您可能想檢查日期是否大于
n_days = Time.days_in_month(month, year)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468129.html
