Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 获取输入并比较与Date.current rails相同的格式_Ruby On Rails - Fatal编程技术网

Ruby on rails 获取输入并比较与Date.current rails相同的格式

Ruby on rails 获取输入并比较与Date.current rails相同的格式,ruby-on-rails,Ruby On Rails,这是表格 <div class="field form-group"> <h6><%= form.label :start_date %></h6> <div class="input-group"> <%= form.date_field :start_date, class: "form-control form-input", requ

这是表格

 <div class="field form-group">
    <h6><%= form.label :start_date %></h6>
    <div class="input-group">
      <%= form.date_field :start_date, class: "form-control form-input", required: true %>
    </div>
  </div>

我想要Date.current的格式,即2020-10-15,以便我可以将其与Date.current进行比较。current

如果您想要以特定格式获取日期,请使用strftime方法。参考:

在您的情况下,请这样使用:

obj.start_date.strftime("%Y-%m-%d")
快乐编码:-)

这是一个彻头彻尾的愚蠢想法 不要在数据库中存储格式化字符串,因为您正在破坏数据建模以解决应用程序中应该解决的一个琐碎的格式化问题

这真的很容易:

Thing.start_date.stftime('%Y-%m-%d')
还有很多其他更优雅的方法,比如助手方法和装饰器

使用适合您的数据库和域的实际时间戳/日期/时间类型列

如果您将日期/时间存储为字符串/整数或其他愚蠢的东西,那么在查询数据时,您(以及任何可怜的sod必须维护您的怪物)将为此付出巨大的代价,因为如果不强制转换,您实际上无法将其用作日期

例如:

Thing.where(start_date: to..from) 
变成怪物:

# This code will only work on Postgres...
Thing.where("TO_DATE(start_date 'YYYY-MM-DD') BETWEEN ? AND ?", to, from)
# This code will only work on Postgres...
Thing.where("TO_DATE(start_date 'YYYY-MM-DD') BETWEEN ? AND ?", to, from)