Ruby on rails 将字符串转换为日期并比较日期

Ruby on rails turn string into date and compare dates

给定以下模型:

class Person

  field :dob, type: String #In the form of YYYY-MM-DD

end

您将如何编写一个仅包含 :dob 值之后的人的范围,比如 2000-1-1?类似于下面的内容:

scope :is_child, -> { where(:dob.to_date > "2000-1-1".to_date) }

使用 Ruby 的 Date class 将日期比较到您的范围内。

你可以试试

scope :is_child, -> {where("? < ?",Date.parse("2001-1-1","%Y-%m-
%d"),Date.parse(self.dob,"%Y-%m-%d"))}

您将日期存储为 ISO8601 格式的字符串,并且 ISO8601 日期字符串比较合理(即字符串比较与相应的日期比较匹配)。这意味着您可以使用简单的字符串操作:

scope :is_child, -> { where(:dob.gt => '2000-01-01') }

尽管如此,您可能希望使用基于当前日期的动态日期而不是 2000-01-01,否则您将不得不每年更新代码,这很容易出错。