2016-07-01 7 views
0

を最適化Iは、以下の少なくとも18レール:条件場合メソッド

def person_age 
    if person_birthdate.present? 
     now = Time.now.utc.to_date 
     begin 
     parsedDate = Date.parse(person_birthdate, '%d/%m/%Y') 

     diff = now.year - parsedDate.year 
     diff -= (diff.years.since(parsedDate) > now ? 1 : 0) 

     if diff < 18 
      errors.add :person_birthdate, 'You should be at least 18' 
     end 
     rescue 
     errors.add :person_birthdate, 'Date not valid' 
     end 
    else 
     errors.add :person_birthdate, 'Date not valid' 
    end 
    end 

あること(「%のD /%M /%Y」の形式で)ユーザの誕生日をチェックする方法しかし、あまりにも多くを持っていますどのようにそれをより良く見えるようにするための任意のアイデア?

+0

それはそうです。どうしてそれをするの?それが日付の列だった場合、Railsはあなたのために解析を処理し、あなたの検証ははるかに簡単になります。 – spickermann

答えて

2

validates_presence_of :person_birthdate # which will generate the "Date is required message" 

とのようなもの。

validates :person_birthdate, presence: true 
validate :check_age, if: -> { person_birthdate.present? } 

private 

def check_age 
    date = Date.parse(person_birthdate, '%d/%m/%Y') 
    unless d > 18.years.ago 
    errors.add(:person_birthdate, 'message here') 
    end 
end 

if: -> { person_birthdate.present? }条件がtrueある場合にのみ、カスタム検証を呼び出すことができます。

+0

'allow_nil:true'はあなたがエラーに陥るのを防ぎません。 'allow_nil:true'は必要ありません。 –

+0

はい、ありがとうございます。私はそれの後に 'if'を追加するだけです。私は答えを更新します。 – Aleksey

1

私が何をしたいことだと思う:あなたはビルトインとカスタム検証を使用する必要があります

def person_age 
    date = Date.parse(person_birthdate, '%d/%m/%Y') 
    unless d > 18.years.ago 
    errors.add :person_birthdate, "You should be at least 18."  
    end 
end 
0

Railsはいくつかの側面では良いですが、ここでは、これらすべてのvalidate[s]はやり過ぎです:あなたは、データベース内の文字列として誕生日を保存するように

def person_age 
    case Date.today - Date.parse(
     person_birthdate, '%d/%m/%Y' 
     ).advance(years: 18) rescue nil 
    when NilClass 
    errors.add :person_birthdate, 'Date not valid' 
    when -Float::INFINITY..0 
    errors.add :person_birthdate, 'You should be at least 18' 
    else puts "Allowed!" 
    end 
end