【问题标题】:Rails: optimizing a methodRails:优化方法
【发布时间】:2016-07-01 07:54:06
【问题描述】:

我有以下方法可以检查用户生日(“%d/%m/%Y”格式)至少为 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

但是 if 条件太多了,知道如何让它看起来更好吗?

【问题讨论】:

  • 您似乎将生日作为字符串存储在数据库中。你为什么这样做?如果它是一个日期列,Rails 会为您处理解析,并且您的验证会容易得多。

标签: ruby-on-rails ruby date if-statement logic


【解决方案1】:

您应该使用内置和自定义验证。

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: -&gt; { person_birthdate.present? } 只允许在条件为true 时调用自定义验证。

【讨论】:

  • allow_nil: true 不会阻止您出错,if 会。 allow_nil: true 不需要。
  • 好的,谢谢。我只是在它之后添加if。我会更新答案。
【解决方案2】:

我想你想要的是:

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

诸如此类:

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

【讨论】:

    【解决方案3】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2012-05-07
      相关资源
      最近更新 更多